You can use this simple function:
function url_get_param($url, $name) {
parse_str(parse_url($url, PHP_URL_QUERY), $vars);
return isset($vars[$name]) ? $vars[$name] : null;
}
See it in action here.
It will return the value of the parameter if it exists in the url, or null
if it does not appear at all. You can differentiate between a parameter having no value and not appearing at all by the identical operator (triple equals, ===
).
This will work with any URL you pass it, not just $_SERVER['REQUEST_URI']
.
Update:
If you just want to know if there is any parameter at all in the URL then you can use some variant of the above (see Phil's suggestion in the comments).
Or, you can use the surprisingly simple test
if (strpos($url, '=')) {
// has at least one param
}
We don't even need to bother to check for false
here, as if an equals sign exists it won't be the first character.
Update #2: While the method using strpos
will work for most URLs, it's not bulletproof and so should not be used if you don't know what kind of URL you are dealing with. As Steve Onzra correctly points out in the comments, URLs like
http://example.com/2012/11/report/cGFyYW1fd2l0aF9lcXVhbA==
are valid and yet do not contain any parameter.