user3041764 user3041764 - 4 months ago 7
PHP Question

Send array as json and read that data

I am encoding array as json and sending it by curl to other file:

$data = array(
"authorizedKey" => "abbad35c5c01-xxxx-xxx",
"senderEmail" => "myemail@yahoo.com",
"recipientEmail" => "jaketalledo86@yahoo.com",
"comment" => "Invitation",
"forceDebitCard" => "false"
);

$data = json_encode($data);

$ch = curl_init('http://localhost/curl/1.php');
$headers = array('Accept: application/json','Content-Type: application/json');

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

echo curl_exec($ch);
curl_close($ch);


Problem is http://localhost/curl/1.php dont recieve any
$_POST
and I dont know how to operate on posted data.

http://localhost/curl/1.php output:

Headers:
Host = localhost
Accept = application/json
Content-Type = application/json
Content-Length = 166
GET:
empty
POST:
empty

Answer

You are sending data by using request body, and you are supposed to get data by request body not $_POST super global. You can use following code to get whole data.

$entityBody = file_get_contents('php://input');