Get current URL with PHP

In this post we will see how to obtain the current URL through a couple of functions with PHP, in addition to obtaining the URL we can also obtain certain details such as the port, protocol and host.

At PHP there are several variables that provide data about the URL that is being executed. We can obtain different data through these variables as it suits us. For example, with the $_SERVER variables of PHP following you can get that URL that we are executing:

  • $_SERVER[«REQUEST_URI»], returns the URL that is being executed, relative to the root of the domain
  • $_SERVER[«PHP_SELF»], returns the script that is being executed, relative to the root of the domain, which may be different than REQUEST_URI
  • $_SERVER[«SERVER_NAME»] Stores the server where the page is hosted

This way we could put the variables together and concatenate them into one to obtain the complete URL easily

$current_url = "http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
echo "$current_url";

We can also obtain more data in addition to the URL, such as the protocol, the host and the port that is being used, below I show you the code to obtain said data:


Once the getURL function has assembled the URL, what we do is decompose it using the parse_url to see the parts that compose it.

$url = getUrl();
$data = parse_url($url);

foreach ($data as $key=>$value) {
  echo "$key: $value 
";
}

$current_url = "http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
echo "$current_url"
?>