« Find a visitor's IP Address with PHP | Main | Save Embedded Media and Other Files in Firefox »

How to Find the Current URL with PHP

The full URL to a page comes in three parts: The domain name, the path to the file then 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:

1. The domain name: www.example.com
2. The path to the page: /example/page.php
3. The query string: name=Bob

So how do you find it all out 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 'HTTP_HOST', 'SCRIPT_NAME' and 'QUERY_STRING' for the three 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:

<?php
  // 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 = "http://" . $domain . $path . "?" . $queryString;
  echo "The current URL is: " . $url . "<br />";
  
  // An alternative way is to use REQUEST_URI instead of both
  // SCRIPT_NAME and QUERY_STRING, if you don't need them seperate:
  $url2 = "http://" . $domain . $_SERVER['REQUEST_URI'];
  echo "The alternative way: " . $url2;
?>

Related Entries

Find a visitor's IP Address with PHP - Nov 01, 2005

How to use PHP in pages with a .html extension (or any other) - Oct 24, 2005

Write text on a dynamically generated image using PHP - Oct 19, 2005

Write Text on to an existing PNG image using PHP - Oct 19, 2005

Generate a Month Calendar In PHP - Oct 19, 2005

How to use the query string in PHP - Oct 19, 2005

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

Adlinks

Creative Commons License
This weblog is licensed under a Creative Commons License.
Powered by
Movable Type 3.2