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:
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.
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.
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:
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; ?>
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.
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.
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.
Thanks u for ur post
[...] How To Find The Current URL In PHP | Learn PHP Online (tags: php tutorial url) [...]
Please show how to connect visitor counter with database in PHP
Usseful post. I waz looking for Query String and i find it here. Thanks
how can i open the face book?if my requested url was not found the server
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
Yes this is a very nice post
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
Great Post, I was looking for this several places and couldn’t find such a clean solution. Thanks a lot
Thanks helped me with collecting info about people
Hi,
interesting article.
One question, how do you get hold of the rewritten URL?
Thanks
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 ??
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!
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
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).
This is awesome sauce, cheers!
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.
[CODE] $canonicalUrl = “http://” . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] .’?’ . $_SERVER['QUERY_STRING'];
$canonical = ”;
[/CODE]
@ 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 }