John Davidson

Why is posting JSON with PHP Curl not working?

0 comments
Message:


I have the following function:


function postCurl($url, $data){
$data = json_encode($data);
$ch = curl_init( $url);
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec( $ch );
curl_close( $ch );

return $result;
}

This function converts a (multidimensional) array to JSON should post it with curl.


The requested url simply returns all post values with:


echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';

I verified with Postman that the requested url is working but when I post via curl I get no result.
The only way I could replicate this issue with Postmanwas sending incorrect JSON so I bypassed the json_encode function and tried a valid JSON string but no result.


I got this function working in the past so I think it must be an issue with the settings.


Any help would be appreciated.



My Answer:
The issue might be with the way you are encoding the data before sending it with cURL.

Try encoding the data using `http_build_query` instead of `json_encode` before setting it as the POSTFIELDS in cURL.

Here is an updated version of your function:

php
function postCurl($url, $data){
$data = http_build_query($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

$result = curl_exec($ch);
curl_close($ch);

return $result;
}


This should properly encode the data before sending it with cURL.

Rate this post

3 of 5 based on 5399 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us