Getting the raw POST or PUT data of a request in ZF2 MVC

If you’re sending raw data to ZF2 over http (perhaps a json document), you can use the “getContent()” method of Zend\Http\PhpEnvironment\Request.

How does this work in practice?

In a controller you might want to do something like this:

1
2
3
4
5
6
7
8
9
<?php
namespace Application\Controller;</code>
 
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
 
class IndexController extends AbstractActionController {
    public function indexAction() {
        $data = $this->getRequest()->getContent();

But if you’re always expecting a certain format, say JSON, a controller plugin could give you back the array or object rather than a lot of json_decode calls in your controllers.

The plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
 
namespace My\Mvc\Controller\Plugin;
 
use Zend\Mvc\Controller\Plugin\Params as ZendParams;
 
class Params extends ZendParams {
 
    public function fromJson() {
        $body = $this->getController()->getRequest()->getContent();
        if (!empty($body)) {
            $json = json_decode($body, true);
            if (!empty($json)) {
                return $json;
            }
        }
 
        return false;
    }
 
}

And then its as simple as:

1
2
public function indexAction() {
    $data = $this->params()->fromJson();

Help! Sometimes getContent() doesn’t return my data.

The method uses file_get_contents(‘php://input’) to get the raw data from the HTTP request. Unfortuantely, the php://input stream can only be read once per process. I did have a plug-in that called file_get_contents(‘php://input’) too, and if $request->getContent() gets called after this, it will be empty!