PHP Simulated Handling of HTTP PUT Request Example

  • 2021-07-09 07:44:04
  • OfStack

For more information on HTTP PUT, please refer to this article: https://www.ofstack.com/article/52515. htm.

There are $_ GET, $_ POST in PHP, but there is no $_ PUT, so if you need to use it, you have to simulate it yourself:


 $_PUT = array();
if ('PUT' == $_SERVER['REQUEST_METHOD']) {
     parse_str(file_get_contents('php://input'), $_PUT);
 }

The data obtained by php://input is raw data, so it needs to be parsed by parse_str.

However, it should be noted that when the form is of enctype= "multipart/form-data" type (that is, the type of uploading file), this method is invalid (php://input is empty at this time). 1 Once PHP finds that the requested Content-Type is multipart/form-data, it will unconditionally handle the form data for you and save it to $_ FILES. At this time, ES40data cannot be obtained, and only one partial gate method can be used

Take apache as an example, modify httpd. conf (to use the RequestHeader syntax, activate the header module first):


<Location "/demo.php">
     RequestHeader set Content-Type foobar
</Location>

By resetting the request header of Content-Type to foobar (as long as it is not multipart/form-data), there is data in php://input at this time, but the original $_ FILES data does not exist, so it is basically only of demonstration significance. If you want to get raw data, you can only generate it according to the data. There is a similar implementation in PEAR: HTTP_Request2_MultipartBody.

Browser 1 is generally only allowed to use GET/POST method. Although PUT method can be sent through JS, it has to write code. Relatively speaking, it is much more convenient to use CURL command under the command line, which is very useful in development and testing, so it is necessary to learn 1:


curl -X PUT http://www.domain.com/demo.php -d "id=1" -d "title=a"

In this way, id and title data will be sent through PUT method, and the code of demo. php is similar to php://input above.


Related articles: