How To Find The Current URL In PHP

In your valiant conquest of the web development industry, you will notice that some scripts will require that you know the current URL the user is browsing to provide certain services. A prime example would be in user management- where we make use of query strings to keep track of users. More practical solutions may even demand that we find the current URL to display relevant ads and increase conversion rates.

PHP has set forth certain global variables that makes this process painfully easy. We will be experimenting with several methods of finding certain parts in the URL within this tutorial. Respectively, they are:

  1. Finding the current domain
  2. Finding the path to the script
  3. Finding the query string (if any)
  4. Using a special short cut method to tie things together

Finding The Current Domain In PHP

If you need the current domain, you can use this neat little snipped below:

<?php
# Using HTTP_HOST

$domain = $_SERVER['HTTP_HOST'];
echo $domain;
?>

If we were to use this directly on this page, the output would be learnphponline.com – notice that it does not include the ‘http://’ or ‘www.’ prefixes. If you are trying to make a link, you could do so by concatenating these prefixes onto the HTTP_HOST server variable.

Finding The Path To The Current Script

If you need to link to the current page, we use the SCRIPT_NAME server variable. We see this in use a lot more than you would think. WordPress installations will link article titles to the same page for several reasons. First, it keeps things user friendly- but it is also great for search engine optimization. Don’t be afraid to follow their example such as the snippet below shows.

<?php 
# Using SCRIPT_NAME

$path = $_SERVER['SCRIPT_NAME'];

echo "Path To Script Example: <a href='$path'>An Article Title</a>";

?>

You will notice that the domain section and query string is left out. Instead we get the script path that links nicely to the current page.

Finding The Query String In a URL

The query string is important in passing variables or authorization information across several different pages in your website. You have probably noticed this before when logging into your favorite website and seen something to this effect: “TheWebsite.com/users/index.php?name=YourName”

Making a query string is actually quite easy. Make a simple PHP file and create a link to the current file, yet concatenate a ternary symbol and assign a variable like this:

  • <a href=’www.yoururl.com/index.php?variable=value’>Test it!</a>

This won’t do anything since we haven’t coded anything to work with the variable. But it will allow us to test the server variable below.

<?php
# Using QUERY_STRING

$queryString = $_SERVER['QUERY_STRING'];

echo "Query: " . $queryString;

?>

Finding The Current URL With Request URI

If you are using MOD REWRITE to make your URLs more user-friendly, there is still a way to get the original URL. By using the REQUEST_URI server variable, we can get the URL given to access the page. So be definition, we bypass any rewrite rules.

<?php
# Using REQUEST_URI

echo "http://" . $_SERVER['HTTP_HOST']  . $_SERVER['REQUEST_URI'];

?>

This saves a little bit of space over the previous examples, since REQUEST_URI can replace the script path and query string server variables. This is best used when you don’t need these variables separated, which you commonly do.

Security Issues To Consider

There are many ways to get the current URL, but the ones mentioned here are the safest. The server variable PHP_SELF is an example of a method that can result in cross-scripting attacks (XSS). Instead make sure you use the SCRIPT_NAME variable as we did above in our examples.

Also make note that header information can be faked. Any variable that includes “HTTP” in it has a potential to be untrustworthy data. There are always verification methods and alternatives to these pitfalls, so you aren’t without options.

A humorous example of how HTTP headers can be faked is with certain security software packages that rewrite referrer information that websites use for analytics. By setting your referrer field to something such as “FBI” or “CIA” you can effectively give the statistics-conscious webmaster a nice scare.

Closing Comments

As a last note, be sure to encode any URL information you make use of if you are using these server variables for your own coding experiments. Otherwise malicious users may take advantage of your inept security tactics and cause havoc on your database.

Comments
  1. raja
    July 23, 2009

    Thanks u for ur post

    Leave a reply
  2. links for 2009-08-19 | Digital Rehab
    August 19, 2009

    [...] How To Find The Current URL In PHP | Learn PHP Online (tags: php tutorial url) [...]

    Leave a reply
  3. Fakir Chand
    September 22, 2009

    Please show how to connect visitor counter with database in PHP

    Leave a reply
  4. OnLine
    November 23, 2009

    Usseful post. I waz looking for Query String and i find it here. Thanks

    Leave a reply
  5. harley
    November 26, 2009

    how can i open the face book?if my requested url was not found the server

    Leave a reply
  6. Ben Johnson
    April 7, 2010

    hi, nice example though if you have strict warning turned on you will recieve the following error because $_SERVER['HTTPS'] is only available if the page is requested by HTTPS that’s why you get Undefined index.

    [code]
    Notice: Undefined index: HTTPS in /var/www/example.co.uk/public/config.php on line 4
    [/code]

    Resolve this by simple changing it to: [code]
    if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}
    [/code]

    Hope this helps

    Leave a reply
  7. Sarthak Vijayrania
    May 28, 2010

    Yes this is a very nice post

    Leave a reply
  8. fazalyazdan
    July 27, 2010

    hi this is nice post but i don’t understand clearly the function of
    $queryString = $_SERVER['QUERY_STRING'];
    please Explain me in detail why we use it .And also in which satuation we use this function. Thank you

    Leave a reply
  9. Mujahid
    August 20, 2010

    Great Post, I was looking for this several places and couldn’t find such a clean solution. Thanks a lot

    Leave a reply
  10. kaki
    October 13, 2010

    Thanks helped me with collecting info about people :)

    Leave a reply
  11. Barton
    November 1, 2010

    Hi,

    interesting article.

    One question, how do you get hold of the rewritten URL?

    Thanks

    Leave a reply
  12. Trivikram
    March 3, 2011

    Hi Thanks for the post. I applied this for my wordpress site, and it is not working. I dont know why ??? Can You Help me ??

    Leave a reply
  13. Aaron W
    March 19, 2011

    Just what I needed. This worked like a charm! I searched other places online for how to do this, but this was the simplest solution I found, and the best explanation. Thanks!

    Leave a reply
  14. FC
    April 2, 2011

    What do you do if you want to find if an anchor tag was used. I want to see if someone came into the page

    test.php vs test.php#some_anchor

    Leave a reply
  15. Nicholas Maietta
    April 13, 2011

    A note to anyone writing a script or piece of software that has to “neutralize” a web address for the purposes of matching against, lets say… a database to pull content… (Such as Commnetivity), you might want to consider that some of the environment variables change under certain circumstances. One of those circumstances would be on an web server (ie, apache) level redirect to serve up a page. A good example is that if direct all traffic to a script using .htaccess, including 403′s (Directory Listing Denied for real directories), Then your normal methods of derriving the URL or URI stuff isn’t going to work and can have you beating your head against the wall. (I have a flat head, i know).

    My recommendation to anyone trying to build a CMS like i did, is simply to understand first how those Environment variables are derrived by the webserver and read the RFC standards that deal with this. Then, before analyzing the URL or URI, you should first use maybe a switch case scenario for determining the http response from the server. Then and only then you can figure out which methods would most likely work.

    These sample document requests are simple, but they can show where bugs might be in your code for deriving a “virtual path” as i like to call it.

    /normalpage.html
    / <- No page, just a fowardslash.
    /?Something
    /?Something=Stupid
    /index.html?Test
    /index.html?Test=Nothing
    /index.?Test
    /index.
    /?
    //
    ///
    /../
    /./
    /somefakefolder/somerealfolder/somefile.html
    /somerealfolder/somefakefolder/somefile.html
    /somerealfolder/

    etc.

    My methods i cannot disclose, as i do have to feed myself, but after 10 years of website developement the oldschool ways, i finally made the crazy move to build a very lightweight but well thought out CMS. Derriving a clean URL for matching against references was a HUGE part of the solution.

    Oh, just for fun, i had to make sure this worked on not just with Apache, but also with other servers… AND had to work with *nix and windows alike. (Mac OS X and higher is based off *nix, so dont think im a mac hater).

    I have now given you a good nugget of information my friends, and i dont mind a little competition if any of you out there are really serious about building a power CMS. Over 2 years of hell to make it… and nearly homeless the whole time. Little food, no real transportation (a bike over 12 miles a day to get wifi to develop the software). I want people to understand that you dont want to build something unless you poor your heart into it (keeping in mind the security of the websites that run on your CMS).

    Leave a reply
  16. Leyton Jay
    August 16, 2011

    This is awesome sauce, cheers!

    Leave a reply
  17. caroline I
    September 5, 2011

    Thanks very much for this clear explanation. I’d also been looking for a while on how to simply get a site’s url as I was redirecting a domain to another and needed the URL as a variable.

    Leave a reply
  18. megainfo
    September 24, 2011

    [CODE]
    $canonicalUrl = “http://” . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] .’?’ . $_SERVER['QUERY_STRING'];

    $canonical = ”;

    [/CODE]

    Leave a reply
  19. Er1c S
    October 4, 2011

    @ FC:
    // How do I find out if someone came from a link with an anchor …
    if ( strpos( $_SERVER['REQUEST_URI'], ‘#some_anchor’) > 0) {
    // you came to #some_anchor
    }

    Leave a reply
Leave a Comment Below »
Your Name
Your Email Address
Your Comment