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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.