How to Get the Current Page URL

In this post I will show you how to get the current page url as shown in address bar using PHP. Extracting the current page's url is very easy in PHP as it provides an array $_SERVER which contains information such as headers, paths, and script locations.

Try running this code and see what you get as output.

<?php

echo $_SERVER["SERVER_NAME"];

?>

If you execute the above mentioned code you will get something like this as output -

www.botskool.com

So $_SERVER["SERVER_NAME"] gives your domain name as output without http://. Now run this code -

 

<?php

$currentURL = "http://";

$currentURL .= $_SERVER["SERVER_NAME"];

$currentURL .= $_SERVER["REQUEST_URI"];

echo "Your complete current page url is ".$currentURL;

?>

Output will be something like this - 

Your complete current page url is http://www.botskool.com/geeks/how-get-current-page-url

And voila! We are done 

An advanced version of the this script is given below - 

 

<?php

function currentURL() {

 $currentURL = 'http';

 if ($_SERVER["HTTPS"] == "on") {

  $currentURL .= "s";

 }

 $currentURL .= "://";

 if ($_SERVER["SERVER_PORT"] != "80") {

  $currentURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];

 } else {

  $currentURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

 }

 return $currentURL;

}

?>

Now to use this function currentURL() simply call it like this wherever you need to use it.

<?php

echo currentURL();

?>

Output is shown below - 

http://www.botskool.com/geeks/how-get-current-page-url

 

Tags: