简体   繁体   中英

How do I tell for a php page if someone came by POST or GET?

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.

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
 }

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

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.

!empty($_POST)

我很确定你可以通过GET和POST访问一个页面,所以这将是IMO最安全的方式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM