PHP Curl json POST not working for me

634 views Asked by At

Hi I'm trying to send a POST request using PHP and Curl. I want to send a JSON similar to this

"json":{
  "testString":"test",
  "testInt":1
}

I have tried this code to accomplish this

curl_init("domain.com");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, '"json":'.$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);

My laravel project that receives the request gets no information with it.

Edit: to explain further, My laravel project gets the request but with no post data attached, none.

2

There are 2 answers

0
Bizmate On

I am not sure why you are using the CUSTOMREQUEST option in curl. Please use http://curl.haxx.se/libcurl/c/CURLOPT_POST.html

Also in your laravel you can check the body by calling http://php.net/manual/en/function.http-get-request-body.php

1
James Taylor On

Assuming $data_string:

$data_string = '"json":{
  "testString":"test",
  "testInt":1
}';

Replace:

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, '"json":'.$data_string);

With:

curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);