Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP decode JSON POST [closed]

Tags:

json

php

I"m trying to receive POST data in the form of JSON. I'm curling it as:

curl -v --header 'content-type:application/json' -X POST --data '{"content":"test content","friends":[\"38383\",\"38282\",\"38389\"],"newFriends":0,"expires":"5-20-2013","region":"35-28"}' http://testserver.com/wg/create.php?action=post

On the PHP side my code is:

$data = json_decode(file_get_contents('php://input'));

    $content    = $data->{'content'};
    $friends    = $data->{'friends'};       // JSON array of FB IDs
    $newFriends = $data->{'newFriends'};
    $expires    = $data->{'expires'};
    $region     = $data->{'region'};    

But even when I print_r ( $data) nothing gets returned to me. Is this the right way of processing a POST without a form?

like image 480
Chris Avatar asked Feb 16 '13 20:02

Chris


People also ask

How get post JSON in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

What does json_decode return?

The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.

What is the use of json_decode in PHP?

The json_decode() function is used to decode or convert a JSON object to a PHP object.


1 Answers

The JSON data you're submitting is not valid JSON.

When you use ' in your shell, it will not handle \" as you suspect.

curl -v --header 'content-type:application/json' -X POST --data '{"content":"test content","friends": ["38383","38282","38389"],"newFriends":0,"expires":"5-20-2013","region":"35-28"}'

Works as expected.

<?php
$foo = file_get_contents("php://input");

var_dump(json_decode($foo, true));
?>

Outputs:

array(5) {
  ["content"]=>
  string(12) "test content"
  ["friends"]=>
  array(3) {
    [0]=>
    string(5) "38383"
    [1]=>
    string(5) "38282"
    [2]=>
    string(5) "38389"
  }
  ["newFriends"]=>
  int(0)
  ["expires"]=>
  string(9) "5-20-2013"
  ["region"]=>
  string(5) "35-28"
}
like image 158
MatsLindh Avatar answered Sep 28 '22 00:09

MatsLindh