tags:

views:

115

answers:

9

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?

+2  A: 
$action = $_GET['action'];

if ($action) {
   // whatever
}

or

if(array_key_exists('action', $_GET)) {

}

Btw the method is called GET. What you mean are parameters.

Felix Kling
Seconds... dammit. But you're a Felix, so it's okay. ;)
middus
@middus: Ah, I remember. Greetings :-D
Felix Kling
A: 

All GET parameters are accessible in the same way.

$username = $_GET['username'];
$action = $_GET['action'];

if ($username) {
   // whatever
}

if ($action == 'editpost') {
   // whatever
}
Sparr
A: 
array_key_exists('action', $_GET)
Ignacio Vazquez-Abrams
A: 
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.

pygorex1
A: 

You can do the following:

if(array_key_exists('action', $_GET)){ // returns a boolean
  // do something
}
middus
A: 

The same way - $_GET is an array

$action = $_GET['action'];

Try print_r( $_GET ) to see what's in it

meouw
A: 

The data carried after the ? is called the query string. You can fetch the entire query string with $_SERVER['QUERY_STRING']

And process it like this:

my $values = array();
my $qs = $_SERVER['QUERY_STRING'];

foreach( explode('&', $qs) as $qsitem ) {
  my($key, $value) = explode('=', $qsitem);
  $values[$key] = $value;
}

then, in your example, $values['action'] == 'editpost'.

Kivin
You must be joking! php does all the busywork for you and stores it in `$_GET`.
middus
Moreover, `my` is a pearl keyword and not valid php. `php -r 'my $values = array();'` will result in `Parse error: syntax error, unexpected T_VARIABLE in ...`
middus
A: 

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')
marvin
A: 

The same way as username:

$action = $_GET['action'];
LucaB