Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve JSON via PHP REST API

Tags:

json

php

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.

like image 834
Leo Stein Avatar asked Dec 20 '22 23:12

Leo Stein


1 Answers

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);
like image 63
Mike Brant Avatar answered Feb 21 '23 19:02

Mike Brant