PHP get current URL

30.Jul.2010

Very often you need to know exact URL of your current page. To get URL of current page, you should just implement following function and apply it, as shown in example below.

1
2
3
4
5
6
function get_URL() {
	$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/") . $s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}

Example of PHP get current URL

Redirect user to a secured page of a website:

1
2
3
4
if(get_URL() == 'http://example.com') {
	header('location: https://example.com');
	die();
}

Example shows only one usage of PHP get current URL function, but you can use it to prevent some page from being shown to specific user group, to connect sharing features on Twitter, Facebook or some other service. You can even use it to make custom pagination.

Function seen on: WebCheatSheet.