PHP Code to Get Current Page’s URL

Posted in Web Development on 1 July 2012 1 comment

It is quite often that we need to redirect users back to current URL. I wrote my own function for this purpose, but then I realized some weaknesses: it cannot capture HTTPS and the port number, which is very important for some websites. Luckily, I found this piece of code from which does the magic:

The PHP Code

function getCurrentURL() {
	$s = empty($_SERVER["HTTPS"]) ? '': ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
echo getCurrentURL();

It works perfectly in returning the following URLs

  • http://localhost/
  • http://localhost/a.html?b=1
  • http://localhost:8080/a.html

Hope this helps.


Posted by Zen on 1 July 2012 • 79,728 visits 1 comment
Tags :

or Subscribe to specific category only :


Wilton says:

It’s a shame you don’t have a donate button! I’d without a doubt donate to this fantastic blog! I suppose for now i’ll settle for book-marking and adding
your RSS feed to my Google account. I look forward to fresh updates and will talk about this site
with my Facebook group. Talk soon!

Leave a Reply

You must be logged in to post a comment.

Previous Post
Next Post