Missing `foo=bar` POST data line in Zend\Http\Request example of generating a formatted HTTP Request from a Request object

If You’re missing the foo=bar line in the output of the example Generating a formatted HTTP Request from a Request object, just add:

$request->setContent($request->getPost()->toString());

right before:

echo `$request->toString();

The original (not working) example (found here):

use Zend\Http\Request;
$request = new Request();
$request->setMethod(Request::METHOD_POST);
$request->setUri('/foo');
$request->getHeaders()->addHeaders(array(
    'HeaderField1' => 'header-field-value1',
    'HeaderField2' => 'header-field-value2',
));
$request->getPost()->set('foo', 'bar');
echo $request->toString();

Following output is expected:

POST /foo HTTP/1.1
HeaderField1: header-field-value1
HeaderField2: header-field-value2

foo=bar

but the real output is:

POST /foo HTTP/1.1
HeaderField1: header-field-value1
HeaderField2: header-field-value2

foo=bar is missing in the real output. This will cause other problems – $client->send($request) will send empty POST data. That’s totally unexpected behavior.

The modified working example:

use Zend\Http\Request;
$request = new Request();
$request->setMethod(Request::METHOD_POST);
$request->setUri('/foo');
$request->getHeaders()->addHeaders(array(
    'HeaderField1' => 'header-field-value1',
    'HeaderField2' => 'header-field-value2',
));
$request->getPost()->set('foo', 'bar');
$request->setContent($request->getPost()->toString());
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo $request->toString();

real output:

POST /foo HTTP/1.1
HeaderField1: header-field-value1
HeaderField2: header-field-value2

foo=bar

After adding this line $request->toString() will return expected values and $client->send($request) finally sends post data set via $request->getPost()->set('foo', 'bar') as expected.

IMO issue #3305 is somehow related to this problem.

Leave a Reply

Your email address will not be published. Required fields are marked *