The
full URL to a web page comes in four parts: The
protocol prefix, the domain name, the
path to the file and the
filename, and the
query string. For example, take the URL
http://www.example.com/example/page.php?name=Bob. The three parts of this are:
- The domain name:
www.example.com - The path to the page:
/example/page.php - The query string:
name=Bob
Here we will show do you how to find current URL with your own PHP scripts...
All of the information we need is stored in the
$_SERVER array, which is accessible from anywhere in your PHP script (and as such is called a superglobal variable), it works like a normal array and the keys we wish to retrieve the values of are
'HTTPS',
'HTTP_HOST',
'SCRIPT_NAME' and
'QUERY_STRING' for the four different parts of the url. Alternatively, if we don't need to have the path to the page and the query string seperate, we can use
'REQUEST_URI'.
The following code should let you find it:
//find out the protocol
$protocol = ($_SERVER['HTTPS'] ? 'https://' : 'http://');
//find out the domain
$domain = $_SERVER['HTTP_HOST'];
//find out the path to the current file:
$path = $_SERVER['SCRIPT_NAME'];
//find out the QueryString:
$queryString = $_SERVER['QUERY_STRING'];
//put it all together...
$url = $protocol . $domain . $path . "?" . $queryString;
echo "The current URL is: " . $url;
//An alternative way is to use REQUEST_URI instead of
//both SCRIPT_NAME and QUERY_STRING:
$url2 = $protocol . $domain . $_SERVER['REQUEST_URI'];
echo "The alternative way: " . $url2;