0

I can't send JSON encoded data via PHP & cURL

my sender code is:

$id = 1;
$txt = "asdsad";
$txt2 = "baszama";
$data = array("id" => "$id", "txt" => "$txt", "txt2" => "$txt2");
$data_string = json_encode($data);
$ch = curl_init('index.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
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))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

index.php:

var_dump($_REQUEST);

My recerieved data:

array(0) { } 

What's the problem in my code?

Aldo
  • 373
  • 3
  • 7
LSG
  • 61
  • 7

2 Answers2

1

PHP expects key=value pairs in the submitted data when it's building the GET/POST/REQUEST superglobals. You're sending a bare string, which has no key. No key, no array entry in the superglobals.

Try

curl_setopt($ch, CURLOPT_POSTFIELDS, "foo=$data_string");

$_REQUEST['foo']

Alternatively, since you're sending via POST, you could use

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

and simply read in the raw text.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0

If you are sending request as JSON string, then you will have to read it as a string:

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

You will find more information here: How to get body of a POST in php?

Community
  • 1
  • 1