Check if url contains parameters

Check if url contains parameters

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

Stefan Bogdanescu

Founder & Senior Architect

Determining Whether to Prefix URL Parameters in PHP

One of the most common pitfalls when constructing URLs dynamically in PHP is deciding whether to prepend a question mark or append an ampersand. The logic seems simple: if the query string already exists, use &; otherwise, use ?. However, relying on regular expressions against server variables like $_SERVER['REQUEST_URI'] often leads to fragile code that breaks on edge cases like trailing slashes or different web server configurations.

The core challenge is distinguishing between a URL with an empty query string (e.g., /foo?) and one without any query parameters at all (e.g., /foo). Your attempted solution using a regex against self.location.href mixes JavaScript syntax with PHP and incorrectly assumes that the presence of ? in the URI guarantees existing parameters. A URI like /path/to/page? contains a delimiter but holds no actual key-value pairs.

In PHP, the most robust approach is to leverage the $_SERVER['QUERY_STRING'] variable or, even better, use the parse_url() function. These methods allow you to inspect the raw string before attempting to modify it.

Inspecting the Query String Directly

The QUERY_STRING server variable contains everything after the ? in the request URI. If this string is empty, there are no parameters. While checking if it is an empty string is straightforward, there is a nuance: some web servers might return a non-empty but invalid string for certain requests. A safer pattern involves using parse_url() to extract just the query component as an array.

Here is how you can safely append a parameter:

$baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// Parse the URL into components
$urlData = parse_url($baseUrl);

if (isset($urlData['query']) && !empty($urlData['query'])) {
    // Query string exists and has content
    $finalUrl = $baseUrl . '&' . $paramName . '=' . $paramValue;
} else {
    // No query string or empty query string
    $finalUrl = $baseUrl . '?' . $paramName . '=' . $paramValue;
}

This logic handles the specific examples you provided. If foobar.com/foo/bar/index.php is requested, parse_url() returns an empty array for the query key (or it doesn't exist), triggering the ? prefix. If foobar.com/index.php?foo=7 is requested, parse_url() extracts foo=7, and the code correctly appends &myparameter=5.

A More Idiomatic Approach with Guzzle or Symfony

While manual string manipulation works, it introduces potential for XSS vulnerabilities if parameters are not properly escaped. If your application framework already provides a way to build URLs, prefer that over raw string concatenation. In frameworks like Laravel, the url() helper or generating redirects via redirect()->fullUrlTo() handles this logic internally and safely encodes the query values.

If you are writing raw PHP, consider using the http_build_query() function for the parameter part, but ensure you handle the separator correctly:

$params = ['myparameter' => 5];

// If we need to append to an existing query string, we must reconstruct carefully
// or use a dedicated URL builder class.

Handling Edge Cases

Be aware that $_SERVER['REQUEST_URI'] includes the path and filename but not the host. That is why you manually concatenate HTTP_HOST. However, this manual reconstruction can be error-prone if your script needs to handle protocol-relative URLs or different base paths.

Another pitfall is trailing slashes. If a user visits /foo/bar/, the query string might still be empty, but the URI ends with a slash. Your logic must ensure that you are checking the query specifically, not just the existence of a ? character in the path. For instance, /path? has a query delimiter but no parameters. Using parse_url() effectively normalizes this because if the string is just /path?, the parsed query part will be empty or null depending on the server implementation, preventing false positives.

Conclusion

The decision to use ? versus & should be driven by an inspection of the parsed URL components rather than a simple regex search for a character. By using parse_url() to check if the query key exists and is non-empty, you eliminate ambiguity regarding empty query strings and ensure your application correctly handles both existing parameters and clean URLs.

Our network