9

I'm am using the Slim Framework Version 3 and have some problems.

$app-> post('/', function($request, $response){
  $parsedBody = $request->getParsedBody()['email'];
  var_dump($parsedBody);
});

result is always:

null

Can you help me ?

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
animatorist
  • 113
  • 1
  • 2
  • 6

4 Answers4

30

When I switch to slimframework version 4, I had to add :

$app->addBodyParsingMiddleware();

Otherwise the body was always null (even getBody())

Thomas
  • 1,231
  • 14
  • 25
5

It depends how you are sending data to the route. This is a POST route, so it will expect the body data to standard form format (application/x-www-form-urlencoded) by default.

If you are sending JSON to this route, then you need to set the Content-type header to application/json. i.e. the curl would look like:

curl -X POST -H "Content-Type: application/json" \
  -d '{"email": "a@example.com"}' http://localhost/

Also, you should validate that the array key you are looking for is there:

$parsedBody = $request->getParsedBody()
$email = $parsedBody['email'] ?? false;
Rob Allen
  • 12,643
  • 1
  • 40
  • 49
  • 3
    I got NULL with var_dump($request->getParsedBody()); when using either PATCH or PUT request. But POST request returns the request body. Is there a different method for PATCH and PUT? – ultrasamad May 30 '17 at 11:05
  • 1
    @ultrasamad Please create a separate question with a minimal PHP code example and the curl command used to show the problem. – Rob Allen May 30 '17 at 15:50
2

Please, try this way:

$app-> post('/yourFunctionName', function() use ($app) {
  $parameters = json_decode($app->request()->getBody(), TRUE);
  $email = $parameters['email'];
  var_dump($email);
});

I hope this helps you!

jcarrera
  • 1,007
  • 1
  • 16
  • 23
  • That will not work for Slim Framework 3, which is what the OP is using. – meun5 Feb 14 '17 at 15:33
  • 1
    Are you sure? It works for me. Look at this http://stackoverflow.com/questions/28073480/how-to-access-a-json-request-body-of-a-post-request-in-slim – jcarrera Feb 14 '17 at 15:44
  • 1
    That is for Slim Framework version 2, not for Slim Framework version 3. The way the requests work was heavily changed from 2 to 3. – meun5 Feb 14 '17 at 15:47
1

In Slim 3, you must register a Media-Type-Parser middleware for this.

http://www.slimframework.com/docs/v3/objects/request.html

$app->add(function ($request, $response, $next) {
    // add media parser
    $request->registerMediaTypeParser(
        "text/javascript",
        function ($input) {
            return json_decode($input, true);
        }
    );

    return $next($request, $response);
});