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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With