Get Current Page URL in PHP

- 1 minute read

The following PHP function will return the URL of the current page:

function currentURL() {
    // Get the protocol
    $currentURL = 'http://';
    if ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] === 443) {
        $currentURL = 'https://';
    }
    // Get the domain or IP address
    $currentURL .= $_SERVER['HTTP_HOST'];
    // Get the port, if it's not 80 or 443
    if ($_SERVER['SERVER_PORT'] !== 80 && $_SERVER['SERVER_PORT'] !== 443) {
        $currentURL .= ':' . $_SERVER['SERVER_PORT'];
    }
    // Get the file path, query parameters, and fragment identifier (if any)
    $currentURL .= $_SERVER['REQUEST_URI'];
    return $currentURL;
}

You can use it by simply calling the currentURL() function, like this:

$url = currentURL();

Lastly, here is a shorter but slightly less readable variant of the currentURL() function with the exact same behavior:

function currentURL() {
    $currentURL = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] === 443) ? 'https://' : 'http://';
    $currentURL .= $_SERVER['HTTP_HOST'];
    $currentURL .= ($_SERVER['SERVER_PORT'] !== 80 && $_SERVER['SERVER_PORT'] !== 443) ? ':' . $_SERVER['SERVER_PORT'] : '';
    return $currentURL . $_SERVER['REQUEST_URI'];
}

Link to this section Conclusion

That’s all!

I hope you found this snippet useful. I’ve personally found this function to be a great starting point for determining the canonical URL of a page and inserting the result into my <link rel="canonical"> tags.