PHP:: Get POST Request Content

2019-08-12 08:37发布

问题:

I'm sending a POST request using WebClient.UploadData() method (C#) to my webserver. The packet sent to my webserver looks like so:

POST / HTTP/1.1
Host: {ip}
Content-Length: {length}
Expect: 100-continue
Connection: Keep-Alive


{buffer_content}

As the {buffer_content} is nowhere assigned in the $_POST array, I have the following question...

Question: How do I read the {buffer_content} with PHP?

I've stumbled upon file_get_contents('php://input'), but I'm unsure whether that is recommended to do.

回答1:

Use the php://input stream:

$requestBody = file_get_contents('php://input');

This is the recommended way to do this and, in PHP 7.0, the only way. Previously, there was sometimes a global variable called $HTTP_RAW_POST_DATA, but whether it existed would depend on an INI setting, and creating it hurt performance. That variable was deprecated and removed.

Beware that prior to PHP 5.6, you can only read php://input once, so make sure you store it.

Once you have your body, you can then decode it from JSON or whatever, if you need that:

$requestBody = json_decode($requestBody) or die("Could not decode JSON");