0

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

$data = array(
  "authorizedKey" => "abbad35c5c01-xxxx-xxx",
  "senderEmail" => "[email protected]",
  "recipientEmail" => "[email protected]",
  "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
3
  • 2
    Consider using Guzzle instead of straight up curl_* functions. Commented Jul 19, 2016 at 11:43
  • Why are you sending it as JSON instead of normal POST data? Commented Jul 19, 2016 at 12:08
  • Bacause it depends of 1.php which has that condition. Commented Jul 19, 2016 at 13:18

2 Answers 2

1

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');
Sign up to request clarification or add additional context in comments.

Comments

1

If you want the data to show up in $_POST, don't encode it as JSON. Just pass the $data array to the CURLOPT_POSTFIELDS option, and don't send the Content-type: application/json header. cURL will then use the normal encoding for POST data, which PHP can convert into fields in the $_POST variable.

2 Comments

You have right, but it is not working with multidimensional array.
stackoverflow.com/a/8224117/1491895 shows how to convert a multi-dimensional array to a URL-encoded query.

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.