0

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

4
  • 1
    This could be related: PHP “php://input” vs $_POST. Commented Sep 18, 2017 at 14:39
  • die(curl_error()); and tell us what that says Commented Sep 18, 2017 at 14:47
  • @delboy1978uk no error, it does send a request to a page, but test1.php is not accepting $_POST when I try to send json string. Commented Sep 18, 2017 at 14:49
  • Wait, both files are on the same server? Why do an HTTP request? Why not just require in test1.php and use $result there? Commented Sep 18, 2017 at 15:18

2 Answers 2

2

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

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

Comments

2

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);

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.