Get Current Page URL Without Query Parameters in PHP

Jul 14, 2023

When you work with websites using PHP, sometimes you need the clean page URL without extra parameters.

For example, your URL may look like this:

https://example.com/page?ref=google&utm_source=ads

But in many real cases, you only need:

https://example.com/page

This is useful when you are tracking pages, saving URLs in the database, or avoiding duplicate links.

In this article, you will learn a simple way to get the current page URL and remove all query parameters using PHP.

<?php
function getCurrentPageURLWithoutParameters() {
    $protocol = 'http://';
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) {
        $protocol = 'https://';
    }
    
    $host = $_SERVER['HTTP_HOST'];
    $requestUri = $_SERVER['REQUEST_URI'];
    
    // Remove query string from request URI
    $requestUri = strtok($requestUri, '?');
    
    return $protocol . $host . $requestUri;
}

// Usage
$currentUrlWithoutParams = getCurrentPageURLWithoutParameters();
echo $currentUrlWithoutParams;
?>