tags:

views:

477

answers:

6

I'd like to have a page in php that normally displays information based on the GET request sent to it. However, I'd like for it to also be able to process certain POST requests. So, how can I tell if any data was sent by POST so I can act on it?

+20  A: 

Use $_SERVER['REQUEST_METHOD'] to determine whether your page was accessed via a GET or POST request.

If it was accessed via post then check for any variables in $_POST to process.

Phill Sacre
Keep in mind, though, that there are more request methods than GET and POST. So don't look if it is GET and otherwise assume it's POST, check it's POST and otherwise assume it's GET.
Lemming
A: 
!empty($_POST)

I'm pretty sure you can access a page via GET and POST, so this would be the safest way IMO

orlandu63
+3  A: 

Check $_SERVER['REQUEST_METHOD']. The documentation is here.

Philip Morton
A: 

If you want to pass the same variables by both POST and GET then you can always use REQUEST which contains parameters from both POST and GET. However, this is generally seen as a security vulnerability as it means that variables can be more easily spoofed.

If you want to test on whether the request was sent POST or GET then you can either:

if($_SERVER['REQUEST_METHOD'] === 'post')
{
    // Do one thing
}
elseif($_SERVER['REQUEST_METHOD'] === 'get')
{
    // Do another thing
}

Or:

 if(!empty($_POST))
 {
     // Process POST
 }
 elseif(!empty($_GET))
 {
     // Process GET
 }
Noah Goodrich
Security vulnerability? That's funny.
orlandu63
I'm with orandu63, variables can be easily (very easily) spoofed whether they are by sent to the server by POST or GET.
Kibbee
I'm only suggesting that using REQUEST is less secure than using POST or GET explicitly. Less Secure == Vulnerability that needn't exist.
Noah Goodrich
+2  A: 

For questions like this, usually about environment variables, here's how I figure them out:

  • Create a foo.php that just calls phpinfo();
  • GET foo.php
  • POST to foo.php
  • Compare the output of phpinfo(); and make my theories about what the behavior is
  • Verify my theory against the docs at php.net

It is much much easier than trying to find the answer in php.net's doc swamp.

Andy Lester
A: 

I use the $_REQUEST variable if have a page and

it to also needs to be able to process certain POST requests

http://is.php.net/manual/en/reserved.variables.request.php

From the manual:

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.