Search code examples
restsymfonyput

PUT request data in Symfony2


The last couple of days I'm trying to build a restful api with Symfony2(2.5 to be precise). I'm building this api according to best practices most apis follow. Therefor I use a PUT http method for updating a resource. However with the PUT method I'm experiencing a problem. Symfony detects that I'm sending data with the PUT method, but the variables I'm sending are nowhere to be found. Here are some code snippets.

The javascript/jquery ajax call

$.ajax({
    url: 'http://www.adomain.com/app_dev.php/api/account/1',
    type: 'PUT',    
    data: 'name=Sander',
    dataType : 'json',
}); 

The php route in routes.php

$collection->add('testbundle_api_update_account', new Route('/api/account/{id}',
array('_controller' => 'TestBundle:Account:apiUpdateAccount'),
array(), array(), '', array(), array('PUT')));

The function in the AccountController

public function apiUpdateAccountAction($id) {
    $request = Request::createFromGlobals();
    var_dump($request->getRealMethod());
    var_dump($request->request->get('name'));
    var_dump($request->query->get('name'));
    die;
}

This outputs

string(3) "PUT"
NULL
NULL

Everything is working fine. The route is found, the function is called. But where is the send data? Any ideas?


Solution

  • This problem is solved by John Smith. It probably has to do with the fact that in php PUT data can only be obtained once with;

    parse_str(file_get_contents('php://input', false , null, -1 , $_SERVER['CONTENT_LENGTH'] ), $_PUT):
    

    In Symfony this is probably done before the function in the controller is called. Therefore, the following doesn't work for PUT:

    $request = Request::createFromGlobals();
    

    The following works:

    $request = $this->getRequest();