Gordonmac Dot Com

Mostly a web development blog

Getting the current URL with PHP

Posted: November 25th, 2007 | Tags: | Posted in: PHP, Tutorials
Note: This tutorial was originally published in 2007. The tips and techniques explained may be outdated.

When I was creating the “Quick Navigation” page section I wanted to add as much helpful stuff as I could and place it in a readily accessible area of the layout. It contains a skip navigation link, a breadcrumb trail and a permanent link for easy bookmarking.

The functionality of those tools are automatically generated using a tiny amount of PHP, and it was whilst writing these functions that I discovered a really awesome little function which returns the complete URL for the current page, along with any URL variables attached.

It also gets my cool vote as it also works with https:// addresses and with sites (normally testing servers) running on different ports, making it a very useful and reusable code snippet. Here it is:

function curPageURL() {
$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;
}

Source: http://www.webcheatsheet.com/PHP/get_current_page_url.php

I hope this will be useful to someone.