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 dev.kanngard.net 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'];
}
 
//usage
echo getCurrentURL();

It works perfectly in returning the following URLs

  • http://localhost/
  • http://localhost/a.html?b=1
  • http://localhost:8080/a.html
  • https://example.com/a/b/c.html?b=1

Hope this helps.

 

Posted by Zen on 1 July 2012 • 32,895 visits 1 comment
Tags :


or Subscribe to specific category only :




  - 1 Comments


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

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Previous Post
«
Next Post
»