PHP Get Current URL
Sometimes it is not as straightforward as one may think to get the current url to use it inside your application. Here is a snippet that I use to fetch the current URL and use it in a script. The current url (whether http or https) is now a local variable that you can do with as you please.
Note: You should groom this value before using in anything sensitive, like a sql query.
You’re currently reading “ PHP Get Current URL ,” an entry on BRADINO
- Published:
- 3.29.07 / 4pm
- Category:
- PHP























Or, slightly shorter:
$url = “http” . ((!empty($_SERVER['HTTPS'])) ? “s” : “”) . “://”.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
Thanks, you rock. :) This was very useful for me.
It helped me too. Thanx!
hmm, this doesn’t seem to return the subdomain (eg. ‘www’)?
Any tips to get that included as well?
Thx
This does not work. Upload the file to
websidename.ext/folder/url.php
…
would only show
websidename.ext/url.php
russell- just use +”www” in the script
Great script! It was short, yet perfect for what I needed. Thank you.
Thats awesome. Short and simple. Took me forever to find this page..all the other sites have a 4-5 line function. This is nice! Thanks a lot!
Lucas-
try using $_SERVER['PHP_SELF'] instead of $_SERVER['REQUEST_URI']
thanks alot! this is really useful and working well
should really be HTTP_HOST instead of SERVER_NAME, and sometimes HTTPS isn’t set when it should be. this should work in most situations:
‘http’.((empty($_SERVER['HTTPS'])&&$_SERVER['SERVER_PORT']!=443)?”:’s’).’://’.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
The code worked perfectly – thank you very much.
Thank you! I spend about an hour searching for a php code to get the current URL, this worked perfect!
Thank you very, very much. I used this to combine a search result page with paging links; ie SEARCH-URL (current url) + &pagenum= + $current_page
This is really a useful script and i am using it. Its working perfectly. Thanks buddies
no port included.
$_SERVER['HTTP_REFERER'];
Forget $_SERVER['HTTP_REFERER']; This is unreliable!
thx for cooding i like this