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/.
Method 1: strpos() Function: The strpos() function is used to find the first occurrence of a sub string in a string. If sub string exists then the function returns the starting index of the sub string else returns False if the sub string is not found in the string (URL).
To check if a url has query parameters, call the includes() method on the string, passing it a question mark as a parameter, e.g. str. includes('? ') . If the url contains query parameters, the includes method will return true , otherwise false is returned.
Existence of an URL can be checked by checking the status code in the response header. The status code 200 is Standard response for successful HTTP requests and status code 404 means URL doesn't exist. Used Functions: get_headers() Function: It fetches all the headers sent by the server in response to the HTTP request.
If you want to get the last part of a URL without the query string, just use the property name window. location. pathname instead of window. location.
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)
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);
}
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
.
Like this:
if (isset($_SERVER['QUERY_STRING'])) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With