How to Get Body of a Post in PHP

How to get body of a POST in php?

To access the entity body of a POST or PUT request (or any other HTTP method):

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

Also, the STDIN constant is an already-open stream to php://input, so you can alternatively do:

$entityBody = stream_get_contents(STDIN);

From the PHP manual entry on I/O streamsdocs:

php://input is a read-only stream that allows you to read raw data
from the request body. In the case of POST requests, it is preferable
to use php://input instead of $HTTP_RAW_POST_DATA as it does not
depend on special php.ini directives. Moreover, for those cases where
$HTTP_RAW_POST_DATA is not populated by default, it is a potentially
less memory intensive alternative to activating
always_populate_raw_post_data. php://input is not available with
enctype="multipart/form-data".

Specifically you'll want to note that the php://input stream, regardless of how you access it in a web SAPI, is not seekable. This means that it can only be read once. If you're working in an environment where large HTTP entity bodies are routinely uploaded you may wish to maintain the input in its stream form (rather than buffering it like the first example above).

To maintain the stream resource something like this can be helpful:

<?php

function detectRequestBody() {
$rawInput = fopen('php://input', 'r');
$tempStream = fopen('php://temp', 'r+');
stream_copy_to_stream($rawInput, $tempStream);
rewind($tempStream);

return $tempStream;
}

php://temp allows you to manage memory consumption because it will transparently switch to filesystem storage after a certain amount of data is stored (2M by default). This size can be manipulated in the php.ini file or by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.

Of course, unless you have a really good reason for seeking on the input stream, you shouldn't need this functionality in a web application. Reading the HTTP request entity body once is usually enough -- don't keep clients waiting all day while your app figures out what to do.

Note that php://input is not available for requests specifying a Content-Type: multipart/form-data header (enctype="multipart/form-data" in HTML forms). This results from PHP already having parsed the form data into the $_POST superglobal.

How to get request content (body) in PHP?

Try this

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

From the manual:

php://input is a read-only stream that allows you to read raw data from the request body.

PHP:: Get POST Request Content

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");

How can I log the full body of a POST request to a file for debugging?

PHP only populates $_POST, when the request Content-Type was either application/x-www-form-urlencoded or multipart/form-data. If you get send anything else, then you have to use php://input to read the raw POST body, and parse it yourself.

The example JSON you have shown appears to be valid - so if json_decode does not give you the expected result here, then your input data was probably not what you expected it to be in the first place.

A basic debugging mistake here is that you are only looking at the final result of multiple “compound” operations. Log what file_get_contents('php://input') returned first of all, to see if that actually is what you expected it to be. If it wasn’t to begin with, then looking only at what json_decode returned, isn’t that helpful.

Cannot read body of post request with php

You are posting binary data.

You are posting an image/wavfile/document.

You can convert it back to what it was and save it to a directory.

$target_dir = "files/";
$target_file = $target_dir . basename($_FILES["file"]["name"]); // file = your input name
$target_file = preg_replace('/\s+/', '_', $target_file);
$uploadOk = 1;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 5000000) {
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "Your file ". preg_replace('/\s+/', '_', basename( $_FILES["file"]["name"])). " is uploaded.";
} else {
echo "Sorry, an error occured";
}
}

How to get full post body using symfony?

Use Request object to get content and then you can use DomCrawler to traverse the nodes and find content.

Example:

use Symfony\Component\DomCrawler\Crawler;

...

public function apiAction(Request $request)
{
$xmlContent = $request->getContent();
$crawler = new Crawler($xmlContent);

$text = $crawler
->filter('node > childnode')
->text();
}

Problem parsing the body of a POST request

There is no post body

i'm putting this url directly in postman, and press send.

I don't use postman myself, but doing this will generate a post request with no data it's the equivalent of:

curl -X POST http://example.com

That's not passing a post body at all. The intent is more like:

curl http://example.com
-H 'Content-Type: application/json'
-d '{"contenu":"Hello","idUser":4}'

This is why file_get_contents("php://input") doesn't return anything.

Note that html form data is available via $_POST - but only for urlencoded POST bodies (which I understand not to be the intent of the question).

Where is the data?

i'm putting this url directly in postman, and press send.

Returning to this quote, the only place for the data is in the url - that is not the normal way to pass data with a post request.

Url arguments are available via $_GET, with the url in the question this code:

<?php
var_dump($_GET);

will output:

array(2) {
["contenu"]=>
string(7) "'Hello'"
["idUser"]=>
string(1) "4"
}

A detail, but note the string includes the single quotes which are in the url (that are probably not desired).

What's the right way to do this?

With a request being made like this:

curl http://example.com
-H 'Content-Type: application/json'
-d '{"contenu":"Hello","idUser":4}'

That data can be accessed like so:

<?php
$body = file_get_contents('php://input');
$data = json_decode($body, true);
$jsonError = json_last_error();
if ($jsonError) {
print_r(['input' => $body, 'error' => json_last_error_msg()]);
exit;
}

echo $data['contenu']; // Hello
echo $data['idUser']; // 4
...

This is very similar to the code in the question, the error appears to primarily be how the request is being made rather than the php logic.

I can't read my POST HTTP request's body with PHP !

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

php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype="multipart/form-data".

(Source: http://php.net/wrappers.php)



Related Topics



Leave a reply



Submit