17

This is an easy one. There seem to be plenty of solutions to determine if a URL contains a specific key or value, but strangely I can't find a solution for determining if URL does or does not have a query at all.

Using PHP, I simply want to check to see if the current URL has a query string. For example: http://abc.com/xyz/?key=value VS. http://abc.com/xyz/.

5 Answers 5

56

For any URL as a string:

if (parse_url($url, PHP_URL_QUERY))

http://php.net/parse_url

If it's for the URL of the current request, simply:

if ($_GET)
Sign up to request clarification or add additional context in comments.

2 Comments

That worked. I was trying if (isset($_SERVER['QUERY_STRING'])) {echo 'has string';} else {echo 'no string';}with no luck. Thanks!
Note (to save others some time): 'just' if ($_GET) (for the current request) works because an empty array is false in a boolean if($x) context. See: php.net/manual/en/types.comparisons.php So indeed no need for count() or empty().
15

The easiest way is probably to check to see if the $_GET[] contains anything at all. This can be done with the empty() function as follows:

if(empty($_GET)) {
    //No variables are specified in the URL.
    //Do stuff accordingly
    echo "No variables specified in URL...";
} else {
    //Variables are present. Do stuff:
    echo "Hey! Here are all the variables in the URL!\n";
    print_r($_GET);
}

Comments

4

parse_url seems like the logical choice in most cases. However I can't think of a case where '?' in a URL would not denote the start of a query string so for a (very minor) performance increase you could go with

return strpos($url, '?') !== false;

Over 1,000,000 iterations the average time for strpos was about 1.6 seconds vs 1.8 for parse_url. That being said, unless your application is checking millions of URLs for query strings I'd go for parse_url.

Comments

3

Like this:

if (isset($_SERVER['QUERY_STRING'])) {

}

2 Comments

You'd think. But when I do a test like if (isset($_SERVER['QUERY_STRING'])) { echo 'has string'; } else {echo 'no string';} I get 'has string' for both of the example urls above.
There's always a $_SERVER['QUERY_STRING'] present, regardless if there was a query string in the url. You have to do if ($_SERVER['QUERY_STRING'] !== '') { echo 'has string' }
0

You can also use if (!$_GET) if you just want to check if the URL doesn't have any parameters at all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.