简体   繁体   中英

PHP Curl json POST not working for me

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM