0

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?

1
  • In ajax, there is a way to post request payload, described here. There is no application/x-www-form-urlencoded needed. Commented Apr 30, 2013 at 9:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation @SamHennessy. I will add an exception in the action, that when coming from the testing environment it reads the needed data like this: http_build_query($this->getRequest()->getPost());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.