Get the current URL using PHP

If you want to get the current page URL (the one that is shown in the browser address bar), you only need a few lines of PHP code. You may want the current page URL in order to use it to build a link back to the current page or some other task like that.

The simple example below shows how you can retrieve the current page URL using PHP. This example assumes that the page is using the HTTP protocol and not the HTTPS protocol. The majority of the time this will be sufficient.

<?php
 
function getPageURL()
{
    $pageURL = 'http://';
 
    if ($_SERVER["SERVER_PORT"] != "80")
    {
      $pageURL .= $_SERVER["SERVER_NAME"] . ":";
      $pageURL .= $_SERVER["SERVER_PORT"];
      $pageURL .= $_SERVER["REQUEST_URI"];
    } 
    else
    {
      $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
 
// call the function and echo the result on the screen
echo getPageURL();
 
?>

And that's it. That's all there is to retrieving the current page URL using PHP. We hope this tutorial was helpful.



Shahbaz Ahmed said:

Mar 25, 2011 at 2:53 pm

I Love this website. It has the basics of MySQL with explanations and examples. It's a great work. Thanks dude.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...