The other day I was writing a script where I was required to consume the current webpage url for in the services I was writing. PHP Server variable is quiet handy for such scenarios as it provide all the parameters passed through the server. Though direct information about the current URL is not provided, it can be formed using the following script:

Add the following code to a page:

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

You can now get the current page URL using echo/var_dump or can consume the same directly by assigning to a variable:

<?php
  echo getCurrentWebpageURL();
?>

 

More details about PHP server variables can be find at http://php.net/manual/en/reserved.variables.server.php

To check out the current values of Server variables, var_dump ($SERVER) can be a handy trick as well.

Leave a Reply

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