user7498776
user7498776

Reputation: 159

PHP Curl Send JSON Data

I am following this tutorial: https://lornajane.net/posts/2011/posting-json-data-with-php-curl

what I am trying to do is POST JSON Data through CURL

$url = "http://localhost/test/test1.php";  
$data = array("name" => "Hagrid", "age" => "36");

$data_string = json_encode($data);                                                                                                                     
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-type: application/json", "Content-Length: " . strlen($data_string)));
$result = curl_exec($ch);
var_dump($result);

when I POST plain text data , I am able to receive that, but when I try through JSON , I am not able to receive that.

Here is my test1.php

test1.php

print_r($_POST);
print_r($_POST);

Any help would be appreciated. Thanks

Upvotes: 0

Views: 374

Answers (2)

TrickyDupes
TrickyDupes

Reputation: 276

JSON data does not come through in $_POST. You need to use file_get_contents('php://input');

You will also need to json_decode it.

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

var_dump($json);

Upvotes: 2

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

When you POST JSON Data through cURL, you have to use php://input. You can use it like:

// get the raw POST data
$rawData = file_get_contents("php://input");

// this returns null if not valid json
return json_decode($rawData, true);  // will return array

php://input is a read-only stream that allows you to read raw data from the request body

The PHP superglobal $_POST, only is supposed to wrap data that is either

  • application/x-www-form-urlencoded (standard content type for simple form-posts) or
  • multipart/form-data-encoded (mostly used for file uploads)

The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST -wrapper doesn't know how to handle that (yet).

Reference

Upvotes: 2

Related Questions