Leo Stein
Leo Stein

Reputation: 157

Retrieve JSON via PHP REST API

I have this cURL function that send json to a REST API:

$url = "https://server.com/api.php";
$fields = array("method" => "mymethod", "email" => "myemail");

$result = sendTrigger($url, $fields);

function sendTrigger($url, $fields){  
    $fields = json_encode($fields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=UTF-8"));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $curlResult["msg"] = curl_exec($ch);
    $curlResult["http"] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $curlResult;
}

On the server, I have this code:

$data = json_decode($_REQUEST);
var_dump($data);
exit();

When I execute the cURL command it returns me this:

Warning:  json_decode() expects parameter 1 to be string, array given in

How's that?

Thanks.

Upvotes: 4

Views: 13889

Answers (2)

Mike Brant
Mike Brant

Reputation: 71422

If you are not using one of the form-encoded content types, PHP will not populate data into $_POST.

You need to get your JSON payload from PHP raw input like this:

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

Upvotes: 11

Kyle
Kyle

Reputation: 4449

In PHP json_decode takes a string and converts it into an object. The $_REQUEST variable is a global variable that contains the contents of $_GET, $_POST, and $_COOKIE (see PHP reference). Most likely, you have a typing error in your code and you probably meant to use $request instead of $_REQUEST.

Upvotes: 0

Related Questions