Simple PHP GET question
UPDATE:
All the methods given below doesn't
work for:
mysite.com?username=me&action=editpost
but only for:
mysite.com?action=editpost
I know how to detect if a particular GET method is in the url:
$username = $_GET['username'];
if ($username) {
// whatever
}
But how can I detect something like this:
http://www.开发者_开发百科mysite.com?username=me&action=editpost
How can I detect the "&action" above?
$action = $_GET['action'];
if ($action) {
// whatever
}
or
if(array_key_exists('action', $_GET)) {
}
Btw the method is called GET
. What you mean are parameters.
All GET parameters are accessible in the same way.
$username = $_GET['username'];
$action = $_GET['action'];
if ($username) {
// whatever
}
if ($action == 'editpost') {
// whatever
}
array_key_exists('action', $_GET)
if (array_key_exists('action', $_GET) && $action = $_GET['action']) {
// action exists
}
However, if an empty string (or anything that evaluates to boolean false) is a valid value, just use this instead:
if (isset($_GET['action'])) {
$action= $_GET['action'];
// Do stuff with $action
}
Using $_GET['action']
when action has not been set will generate a notice, depending on the error reporting level.
You can do the following:
if(array_key_exists('action', $_GET)){ // returns a boolean
// do something
}
The same way - $_GET is an array
$action = $_GET['action'];
Try print_r( $_GET )
to see what's in it
the parameters in the url are assigned to $_GET array from left to the right.
If you have something like
?username=me&action=editpost&somekey=somevalue&action=&someotherkey=someothervalue
then first 'editpost' will be assigned as action but then it will be replaces as '' and as a result
$_GET['action'] = ''; (instead of 'editpost')
The same way as username:
$action = $_GET['action'];
精彩评论