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?
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.
!empty($_POST)
I'm pretty sure you can access a page via GET and POST, so this would be the safest way IMO
Check $_SERVER['REQUEST_METHOD']
. The documentation is here.
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
}
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.
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.