I submit as POST to a php page the following:
{a:1}
This is the body of the request (a POST request).
In php, what do I have to do to extract that value?
var_dump($_POST);
is not the solution, not working.
I submit as POST to a php page the following:
{a:1}
This is the body of the request (a POST request).
In php, what do I have to do to extract that value?
var_dump($_POST);
is not the solution, not working.
If you have installed HTTP PECL extension, you can make use of the
http_get_request_body()
function to get body data as a string.Check the
$HTTP_RAW_POST_DATA
variablehttp_get_request_body()
was explicitly made for getting the body ofPUT
andPOST
requests as per the documentation http://php.net/manual/fa/function.http-get-request-body.phpA possible reason for an empty
$_POST
is that the request is notPOST
, or notPOST
anymore... It may have started out as post, but encountered a301
or302
redirect somewhere, which is switched toGET
!Inspect
$_SERVER['REQUEST_METHOD']
to check if this is the case.See https://stackoverflow.com/a/19422232/109787 for a good discussion of why this should not happen but still does.
To access the entity body of a POST or PUT request (or any other HTTP method):
Also, the
STDIN
constant is an already-open stream tophp://input
, so you can alternatively do:From the PHP manual entry on I/O streamsdocs:
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://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
, whereNN
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.If you have the pecl/http extension installed, you can also use this: