Tony Montana
Tony Montana

Reputation: 133

file_get_contents('php://input') empty in Unit Test

I'm using Zend-Framework and PHP-Unit.


MY SETUP

I have a html form:

<form method="post" action="/my-module/my-controller/do">
    <input type="text" name="var" value="my value" />
    <input type="submit" value="sumit" />
</form>

This is the equivalent unit test:

public function test_myForm ()
{
    $this->request->setMethod('POST')->setPost(array(
        'var' => 'my value'
    ));
    $this->dispatch('/my-module/my-controller/do');
}

The controller action looks like this (for testing purpose):

public function doAction ()
{
    print_r($_POST);
    echo "\n -------------------- \n";
    print_r(file_get_contents('php://input'));
    echo "\n -------------------- \n";
    die;
}

THE RESULTS

If I submit the form on the browser I get this result:

Array ( [var] => my value )
--------------------
var=my+value
--------------------

But if do the unit test, this is the output:

Array ( [var] => my value )
--------------------

--------------------

MY QUESTION

The code "file_get_contents('php://input')" returns an empty string I don't know why.

For the application I'm working on, it is important to read the post data like this "file_get_contents('php://input')" and not just use $_POST.

Anyone an idea why this happens and how to solve it?

Upvotes: 0

Views: 3000

Answers (1)

SamHennessy
SamHennessy

Reputation: 4326

php://input is a read only wrapper. $this->request->setMethod('POST')->setPost(array('var' => 'my value')); is only going to write to $_POST. This is a case where PHP is not testable in the way you want. An alternative would be to use $HTTP_RAW_POST_DATA, but that could require some configuration changes. You would also not be able to use the ZF helpers to set the data in your set, you would need to set it directly in your test case. For a non "multipart/form-data" data you should be able to do encode an array using http_build_query to simulate the data.

Upvotes: 1

Related Questions