Better way to get current page full URL in PHP

02nd, January 2018 By

When we are working in php lot of time in code , we need to get the current page of the URL.There is not any directly function that we will get current page all URL in core PHP.Here we will creating a function that will get the URL of the current page.


<?php
function MyCurrentURL() {
                 $url = 'http';
          if ($_SERVER["HTTPS"] == "on")
            {
              $url .= "s";
             }
            $url .= "://";
      if ($_SERVER["SERVER_PORT"] != "80") {
            $url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
           } else {
             $url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
          }
 return $url;
}
?>

Now you can call this function to any where you want to show current page URL like this.

  echo MyCurrentURL();

Here the $_SERVER Variables that we used to get current page URL:-

$_SERVER[“SERVER_NAME”]  =  The name of the server host under which the current script is executing.

$_SERVER[“REQUEST_URI”]  =  The URI which was given in order to access this page; for instance, like /index.php.

$_SERVER[“REQUEST_PORT”]   =  Its is the port on the server machine being used by the web server for communication.   For default setups, this will be 80.

$_SERVER[“HTTPS”]  = Set to a non-empty value if the script was queried through the HTTPS protocol.

By using these variable in php we will get current page url.Hope this will help you.

Leave a Reply

Your email address will not be published. Required fields are marked *