always_populate_raw_post_data - Trouble accessing request payload from Backbone create

loxyboi picture loxyboi · Feb 2, 2015 · Viewed 21.6k times · Source

I am trying to save a collection to my database RESTfully using Backbone.js with the SLIM php framework running on my server.

Here is my collection:

var newUser = this.collection.create(
    formData,
    {
        wait: true,
        success: $.proxy(function() {
            this.collection.currentUser = newUser;
            App.Router.navigate('', { trigger: true });
        }, this)
    }
);

Here is my SLIM route:

$api->post('/users', function() use($api, $db) {

    $request = $api->request()->post();

    $api->response()->header('Content-Type', 'application/json');

    $result = $db->users()->insert($user);

    if( $result ) {
        echo json_encode(array(
            'id' => $result['id']
        ));
    }
    else {
        echo json_encode(array(
            'status' => false,
            'message' => 'error_creating_user'
        ));
    }

});

$api->run();

When calling create() on my collection, I get a deprecation warning in the server's response:

Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0

I have followed these instructions and done the following:

I have added this before my routes:

ini_set('always_populate_raw_post_data', '-1');

and from within my POST route I have tried to receive the request payload like so:

$request = file_get_contents('php://input');

After this change to my code, the response I am getting has remained the same...

EDIT

The error occurs even with an empty callback....

$api->post('/users', function() use($api, $db) {

    // nothing

});

Answer

Mika Tuupola picture Mika Tuupola · Feb 3, 2015

There is a bug in PHP 5.6. Default value of always_populate_raw_post_datais 0. This causes PHP to throw warnings even if your code does not use $HTTP_RAW_POST_DATA. Some claim it happens when calling header() after some text has already been outputted. Trying to use ini_set()does not help.

You must change the config directly in php.ini instead.

always_populate_raw_post_data = -1

Related discussion in PHP internals.