note 98142 deleted from function.http-get-request-body by sobak
| From: | sobak@php.net | Date: | Sun, 04 Dec 2016 07:20:43 +0000 |
| Subject: | note 98142 deleted from function.http-get-request-body by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208047@lists.php.net to get a copy of this message | ||
Note Submitter: Tim Trinidad
----
It seems that there is some weird behavior when using http_get_request_body() with
fopen('php://input'). Specifically, reading the input with the
fopen('php://input') routine before calling http_get_request_body() on a PUT HTTP request.
Here are some examples:
A POST request:
*********************************************************
PUT http://example.com/requestbodytest.php
HTTP/1.1
Host: example.com
Keep-Alive: 300
Connection: keep-alive
Content-Type: text/xml
Content-Length: 58
<?xml version="1.0" encoding="utf-8" ?>
<body>test</body>
*********************************************************
with the following script:
*********************************************************
<?php
$body = '';
$fh = @fopen('php://input', 'r');
if ($fh)
{
while (!feof($fh))
{
$s = fread($fh, 1024);
if (is_string($s))
{
$body .= $s;
}
}
fclose($fh);
}
print("-------------- PHP Input Stream ----------------\n$body\n\n");
$body2 = http_get_request_body();
print("---------- http_get_request_body() -------------\n$body2\n\n");
?>
*********************************************************
outputs this:
*********************************************************
-------------- PHP Input Stream ----------------
<?xml version="1.0" encoding="utf-8" ?>
<body>test</body>
---------- http_get_request_body() -------------
<?xml version="1.0" encoding="utf-8" ?>
<body>test</body>
*********************************************************
The same request to the same script using an HTTP PUT request, however, outputs this:
*********************************************************
-------------- PHP Input Stream ----------------
<?xml version="1.0" encoding="utf-8" ?>
<body>test</body>
---------- http_get_request_body() -------------
*********************************************************
It seems a valid workaround is to put a call to http_get_request_body() to cache the body content
before an expected read to php://input (i.e. simply calling the function without manually storing
the result caches the content for subsequent calls).