How to get and change URL variable PHP

How to get and change URL variable PHP

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to get and change URL variable PHP

When building web applications, appending parameters to a query string without resetting it is a common source of data corruption. Consider a scenario where a user is on a URL containing parent/child?a=1&b=2&c=3. If you simply echo the current $_SERVER['REQUEST_URI'] and append a new parameter like &d=test, every click on the link adds another d variable instead of replacing the existing one. This results in an infinite chain of parameters: ...&d=test1&d=test2&d=test1.

This behavior occurs because $_SERVER['REQUEST_URI'] returns the raw string from the browser, including any query string already present. When you concatenate a new parameter with an ampersand (&) to this string, the server treats it as an additional key-value pair rather than an update. To change a variable's value, you must first strip the existing query string, modify the target variable, and then reattach the cleaned query string (if any other parameters remain).

Stripping the Existing Query String

The core of solving this problem lies in parsing the $_SERVER['REQUEST_URI'] to separate the path from the query parameters. You can use the built-in parse_url() function for this purpose. This function returns an associative array containing the host, port, path, and query string components.

Here is a robust pattern to replace a specific variable:

$currentUri = $_SERVER['REQUEST_URI'];

// Parse the URI into components
$parts = parse_url($currentUri);

if ($parts) {
    // Extract the query string part, if it exists
    $queryString = isset($parts['query']) ? $parts['query'] : '';

    // Parse the query string into an array of parameters
    $params = [];
    if (!empty($queryString)) {
        parse_str($queryString, $params);
    }

    // Modify or remove the specific variable (e.g., 'd')
    // To change it:
    $params['d'] = 'test1'; 
    
    // To remove it entirely, simply unset it:
    // unset($params['d']);

    // Reconstruct the query string from the modified parameters
    $newQueryString = http_build_query($params);

    // Combine path and new query string
    $newUri = ($parts['path'] ?: '') . 
              (empty($newQueryString) ? '' : '?') . 
              $newQueryString;

    // Generate the link
    echo '<a href="' . htmlspecialchars($newUri) . '">LINK 1</a>';
} else {
    // Handle case where parse_url fails or returns empty
    // Ensure you still handle the base path correctly if no query exists
}

Alternative: The ? vs & Logic

If your goal is strictly to ensure a variable is set to a new value and you don't care about preserving other unrelated parameters, there is a simpler conditional approach. However, this requires detecting whether the current URL already contains the parameter name.

You can use strpos() to check for the presence of the parameter key:

$requestUri = $_SERVER['REQUEST_URI'];
$paramName = 'd';
$newValue = 'test1';

// Check if the parameter already exists in the query string
if (strpos($requestUri, $paramName) !== false) {
    // Parameter exists; replace it. 
    // This regex replaces the entire "key=value" segment for that specific key.
    // It assumes standard URL encoding where the key appears before '='.
    $modifiedUri = preg_replace('/\b' . preg_quote($paramName, '/') . '=[^&]+/', $paramName . '=' . urlencode($newValue), $requestUri);
} else {
    // Parameter does not exist; append it with a '?' if the path is clean, or '&' if there is an existing query.
    if (strpos($requestUri, '?') === false) {
        $modifiedUri = $requestUri . '?' . urlencode($paramName) . '=' . urlencode($newValue);
    } else {
        $modifiedUri = $requestUri . '&' . urlencode($paramName) . '=' . urlencode($newValue);
    }
}

Why http_build_query is Often Safer

While the regex approach works, relying on regular expressions for URL manipulation can be brittle. A more reliable method involves splitting the URI into its path and query components using parse_url(), rebuilding the parameter array with parse_str(), modifying that array, and then reconstructing the string with http_build_query().

This workflow handles edge cases better, such as:

  • Ordering: http_build_query() maintains the order of parameters based on the array keys, though standard GET requests generally treat them as unordered.
  • Encoding: It automatically applies URL encoding to values that contain spaces or special characters.
  • Empty States: If you decide to remove a parameter by unsetting it from the array, http_build_query() will naturally omit it from the final string, preventing empty variables.

Performance and Context Considerations

In high-traffic environments, parsing every request URI can add negligible overhead compared to database queries or external API calls. However, if this logic is executed inside a loop (e.g., building a list of links for all columns in a table), ensure you are not duplicating the parsing logic unnecessarily.

If you are working within a larger framework like Laravel, consider leveraging its url() helper or route models to handle parameter updates safely, abstracting the raw $_SERVER logic away from your views. While direct manipulation of $_SERVER['REQUEST_URI'] is powerful for dynamic link generation, always remember that client-side URL changes do not alter server state; they only dictate how the browser requests resources.

For developers looking to manage complex routing and query parameters with less boilerplate, exploring dedicated routing libraries or package managers can streamline this process further. Resources like https://laravelcompany.com often cover advanced routing strategies that might simplify these specific parameter manipulation tasks if you are migrating from raw PHP logic.

Our network