• DE
  • ES
  • EN
  • NL
Google+twitterfacebook

Blog

PHP: Determine the full URL of the current page


Published on Monday October 16, 2017 by Jeroen Derks.

Sometimes you want to know in a simple PHP script what the current URL (the URL through which the PHP script is called) is. When I was looking for a solution without reinventing the wheel, I actually found no piece of PHP code that met my expectations. So let me try it as well.

From which components does a URL consist?

The format of a URL looks like this:

	protocol://username:password@host:port/path?query#fragment

This URL format is not only used for the World Wide Web. For example, it is also used to communicate or configure the required data for access to a database. Since everyone uses URLs almost daily, I do not need to describe the different parts of the URL further.

I assume that if you want to use the full URL in your PHP code, you do not want to include the credentials (username and password) to prevent them from being used in an undesired way. Also, the fragment will never be passed through the CGI interface so you can not use it either.

Which data are available to you in PHP?

Using the function phpinfo() for example, you can see in PHP which data is available to you to determine the current URL:

Screen shot of phpinfo() output

The solution?

Using this we can generate the following function:

<?php
	function get_current_url()
	{
		$url = false;

		// check whether this script is being run as a web page
		if (isset($_SERVER['SERVER_ADDR']))
		{
			$is_https	= isset($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS'];
			$protocol   = 'http' . ($is_https ? 's' : '');
			$host       = isset($_SERVER['HTTP_HOST'])
							? $_SERVER['HTTP_HOST']
							: $_SERVER['SERVER_ADDR'];
			$port       = $_SERVER['SERVER_PORT'];
			$path_query = $_SERVER['REQUEST_URI'];

			$url = sprintf('%s://%s%s%s',
				$protocol,
				$host,
				$is_https
					? (443 != $port ? ':' . $port : '')
					: ( 80 != $port ? ':' . $port : ''),
				$path_query
			);
		}

		return $url;
	}

Bonus

As a bonus, I give you English manual page for the get_current_url() function.
And the gist URL is: https://gist.github.com/Magentron/05ee3b8f62886878c2f1c3d76e8e3696

If you have any improvement or suggestion to share, please leave a message via the link below.

Please let me know if this article has been useful to you! (or not)