PHP Detect if any URL variables have been set
I have a webpage to which any amount of URL varibales could be set.. examples:
- index.php?source=lol
- index.php?source=lol&sub=haha
- index.php?aff=123
- index.php?keyword=pizza
I want a way that I can detect that any url variable has been set, if a url variable has been set I w开发者_开发技巧ant to print something on the page. Any ideas? I couldn't find anything on Google about this.
count($_GET);
will return the number of parameters in the URL. Use if (count($_GET) > 0)
to test for their presence.
For example:
if (count($_GET) > 0){
print "You supplied values!";
} else {
print "Please supply some values.";
}
Check isset($_GET['var_name'])
http://php.net/isset
You can see if a variable has been set using isset
or array_key_exists
:
if (isset($_GET['source']))
doSomething();
You can loop over all the querystring variable like this:
foreach ($_GET as $key => $value)
echo htmlspecialchars($key) . ' is set to ' . htmlspecialchars($value);
More general:
if (count($_GET)) {
foreach ($_GET as $key => $value) {
echo "Key $key has been set to $value<br />\n";
}
}
If you want to check if any variables has been sent, use the function below.
function hasGet()
{
return !empty($_GET);
}
if (hasGet()) {
echo "something on the page";
}
since $_GET returns an array, it might be safer to check its size using sizeof() function
Example:
if(sizeof($_GET)>0){
/*you had passed something on your link*/
}else{
/*you did not passed anything on your link*/
}
精彩评论