PHP to check if a URL contains a query string
Asked Answered
C

5

16

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/.

Creekmore answered 23/10, 2011 at 3:52 Comment(0)
K
55

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)
Kristlekristo answered 23/10, 2011 at 3:54 Comment(2)
That worked. I was trying if (isset($_SERVER['QUERY_STRING'])) {echo 'has string';} else {echo 'no string';}with no luck. Thanks!Creekmore
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().Dichotomize
R
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);
}
Redoubt answered 23/10, 2011 at 4:1 Comment(0)
N
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.

Napper answered 15/3, 2017 at 9:23 Comment(0)
F
3

Like this:

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

}
Fairtrade answered 23/10, 2011 at 3:53 Comment(2)
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.Creekmore
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' }Foreside
V
0

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

Vo answered 2/7 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.