Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : URL Functions

URL Functions

Introduction

Dealing with URL strings: encoding, decoding and parsing.

Requirements

No external libraries are needed to build this extension.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension has no resource types defined.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following constants are meant to be used with parse_url() and are available since PHP 5.1.2.

PHP_URL_SCHEME (integer)
PHP_URL_HOST (integer)
PHP_URL_PORT (integer)
PHP_URL_USER (integer)
PHP_URL_PASS (integer)
PHP_URL_PATH (integer)
PHP_URL_QUERY (integer)
PHP_URL_FRAGMENT (integer)

Table of Contents

base64_decode — Decodes data encoded with MIME base64
base64_encode — Encodes data with MIME base64
get_headers — Fetches all the headers sent by the server in response to a HTTP request
get_meta_tags — Extracts all meta tag content attributes from a file and returns an array
http_build_query — Generate URL-encoded query string
parse_url — Parse a URL and return its components
rawurldecode — Decode URL-encoded strings
rawurlencode — URL-encode according to RFC 1738
urldecode — Decodes URL-encoded string
urlencode — URL-encodes string

Code Examples / Notes » ref.url

dbz

You should have named your form field "organization[]" (notice the square brackets), instead of just organization. When using square brackets, the get/post request is interpreted by PHP as an array.
If you follow this example you'll understand why it works the way it does:
<?php
$organization = 92;
$organization = 93;
// The second asignment overwrites the value of the first
// asignment. $organization === 93.
$organization[] = 92;
$organization[] = 93;
// The above is interpreted as appending data to an array
// named "$organization". $organization is an array
// consisting of the values 92 AND 93.
?>
When submitting form fields with appended square brackets to their name, PHP interprets the submission using the same logic exposed above. Thus PHP automatically creates an array with all selected options if "$organization[]" is used as the field name.
Regards,
  Daniel Berstein.


dday

When using a multiple select on a form, I ran into a little issue of only receiving the last value form the select box.
I had a select box named organization_id with two values (92 and 93).
To get the values of both, I had to use the following:
$temp_array = split("&", $_SERVER['QUERY_STRING']);
foreach($temp_array as $key=>$value){
if(substr($value, 0, 15) == "organization_id"){
$_GET['organizations'][] = substr($value, 15, strlen($value));
}
}
this results in a $_GET array like this :
(
   [page] => idea_submission
   [organization_id] => 93
   [organizations] => Array
       (
           [0] => =92
           [1] => =93
       )
)


verdy_p

Warning: when the PHP engine runs for your hosted web site, it may execute on a domain name which is completely different than the one the user requested in its browser. Many free web hosting site use proxies and/or multiple DNS entries for your hosted web site. This means that:
- the IP of the web server can change if multiple DNS entries are present (there may be several web servers running concurrently)
- reverse DNS name from the IP may give different domain name over time, or if the domain name is a CNAME only for a virtual web server hosting many domains
- the server running PHP may be different than the web server
- the web server may be hidden behind a proxy which balances the load between a farm of servers
- the queried host name in the HTTP headers may be different than the queried host name in the browser, if behind a redirecting proxy
- the actual path name of the ressource may be also different, with additional path elements: this is very common on free hosting servers, where you get a virtual CNAME domain, which gets translated by a proxy into an actual web server, and a domain-specific document root directory
So when thinking about using absolute path names you can retreive from PHP, beware that this may not be accurate to insert as absolute URL's in the HTML code built with PHP.
The best solution is then to ALWAYS USE relative URLs to reference documents and form scripts on your local server !
This applies to $PHP_SELF too, because it's an absolute pathname: don't use it directly but you can safely use basename($PHP_SELF) to reference your script within HTML forms:
<?
$self=basename($PHP_SELF);
?>
<HTML><HEAD>
...
</HEAD><BODY>
<FORM method="GET" action="$self">
...
</FORM>
</BODY></HTML>


tumor

To check if a URL is valid, try to fopen() it. If fopen() results an error (returns false), then PHP cannot open the URL you asked. This is usually because it is not valid...

jrg45

Note that $_SERVER["HTTP_REFERER"] may not include GET data that was included in the referring address, depending on the browser.  So if you rely on GET variables to generate a page, it's not a good idea to use HTTP_REFERER to smoothly "bounce" someone back to the page he/she came from.

ignacio paz posse

Note on the above: the point is that is that using $_SERVER['QUERY_STRING'] along with $PHP_SELF we will have passed whatever variables are already appended (as they might be needed for database queries)
example, given the following url: http://www.your_domain/somepage.php?variable=1;
using $PHP_SELF" we are passing
[scheme]:(http://), [host]: www.your_domain/  and [path]: somepage.php
adding $_SERVER['QUERY_STRING'], we pass that, plus [query]: variable=1


verdy_p

Note also that the URL shown in $HTTP_REFERER is not always the URL of the web page where the user clicked to invoke the PHP script.
This may instead be a document of your own web site, which contains an HTML element whose one attribute references the script. Note also that the current page fragment (#anchor) may be transmitted or not with the URL, depending on the browser.
Examples:
<FRAME src="your-page-script.php"8>
<IMAGE src="your-image-script.php">
In such case, browsers should transmit the URL of the container document, but some still persist in using the previous document in the browser history, and this could cause a different $HTTP_REFERER value be sent when the user comes back to the document referencing your script. If you wanna be sure that the actual current document or previous document in the history is sent, use client-side JavaScript to send it to your script:
<SCRIPT language="JavaScript"><!--
document.writeln('<FRAME src="your-page-script.php?js=1&amp;ref=' +
document.location + '">');
--></SCRIPT><NOSCRIPT>
<FRAME src="your-page-script.php?js=0">
</NOSCRIPT>
And then check the value of $js in your page script to generate appropriate content when the remote user agent does not support client-side scripts (such as most index/scan robots, some old or special simplified browsers, or browsers with JavaScript disabled by their users).


job oberio

just want to share some tip:
my visitors usually type http://pinoylinux.com
in their browser (note: no www)
and i want them to automatically change the url
to use www.
(from http://pinoylinux.com to http://www.pinoylinux.com)
The solution is:
you can add the ff code to your existing index.php script
<?php
if  ($HTTP_HOST=="pinoylinux.com")
{
header("Location: http://www.pinoylinux.com"); die();
}
~~~ your existing codes here ~~~
?>
hope that helps


chemanfit

just a side note to the above you will need to add the ?
example
$page=$PHP_SELF."?".$_SERVER['QUERY_STRING'];


postmaster

If you want to get the filename requested on a global error page like a 404, just use this code...
// get the full var...
$page = $HTTP_SERVER_VARS["QUERY_STRING"];
// part[1] is the url...
// part[0] is the http code (404, etc).
if(strpos($page,";")>0) {
  $pageParts = explode(";",$page);
  $page = $pageParts[1];
}
// get only the filename...
$page = basename($page);


tappertzhofen

If you got a server which got only one subdomain and you can't add a subdomain you can easily create your own "subdomain script". You may create a file "index.php" or what ever your defaul filename is in the webpage root directory and add the following PHP Code:
<?php
// Get possible subdomain
$full_url = sprintf($HTTP_HOST);
$subdomain = "";
for($i = 0;$i<=strlen($full_url);$i++)
{
 $dummy = substr($full_url,$i,1);
 if($dummy == ".")
 {
   break;
 }
 $subdomain = $subdomain.$dummy;
}
// Get Subdomain List
if ($subdomain <> "www")
{
 switch($subdomain)
 {
   case "download":
     $real_url = "http://www.mydomain.com/download/index.php";
     break;
   case "contact":
     $real_url = "http://www.mydomain.com/contact.php";
     break;
 }
 header( "location: $real_url\r\n" );
?>


stephane-wantiez

if you do this, it will be easier :
echo "http://{$HTTP_HOST}{$REQUEST_URI}";


pawel dot lesniak

How do I go and encode an URL, but EVERYTHING is encoded. As such:
http://www.domain.com/
...becomes...
%68%74%74%70%3a%2f%2f%77%77%77%2e%64%6f%6d%61%69%6e%2e%63%6f%6d
This one does what you want
<?php
$text = 'http://www.domain.com/';
$output = '';
$tab_text = str_split($text);
foreach ($tab_text as $id=>$char){
 $hex = dechex(ord($char));
 $output .= '%' . $hex;
}
echo $output;
?>


regix11

How do I go and encode an URL, but EVERYTHING is encoded. As such:
http://www.domain.com/
...becomes...
%68%74%74%70%3a%2f%2f%77%77%77%2e%64%6f%6d%61%69%6e%2e%63%6f%6d
(note: I hand-url-encoded it)
Here is the URL-Encoded url, clickable (the http:// part shows up twice)
http://%68%74%74%70%3a%2f%2f%77%77%77%2e%64%6f%6d%61%69%6e%2e%63%6f%6d


php

Following method do not show the URL in user browser (as the author claimed) if the code resides in the source page of  FRAME or IFRAME (say SRC="sourcepage.php") . In that case the URL of the SOURCE page is displayed.
$url = sprintf("%s%s%s","http://",$HTTP_HOST,$REQUEST_URI);
echo "$url";
Expected result: http://localhost/urltest/framedpage.php
Actual result: http://localhost/urltest/sourcepage.php


martin

Each %xx represents a letter. You would need to remove %68%74%74%70%3a%2f%2f (http://) from the beginning.

ignacio

/*
May be this is obvious but helps me since I found it:
If I want to append a variable to the url and pass it to the same page. ( in this example I'm using action=email to include an email form on the user click) i do:
*/
// ...
<a href="<? echo $PHP_SELF,'?',$_SERVER['QUERY_STRING'],'&action=email' ?>">email to us</a>
// ...
/* somewhere in the the page (in my case at the bottom) I have: */
<? if ($action=='email') include('emailForm.htm'); ?>


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker