Reputation: 61
cURL is new to me. I'm trying to integrate an api via PHP cURL. The api that I'm trying to access requires that parameters be sent as key-value pairs, not json. Their example cURL request in their docs is:
curl -i -X POST -d 'api_key=my_api_key' -d
'[email protected]' -d "first_name=Joe" -d "last_name=Doe" -d
"cust_id=cus_401"
https://serviceurl.com/api/create
My code is apparently sending empty parameters to their api.
$service_url = 'https://serviceurl.com/api/create';
$curl = curl_init($service_url);
$email = $this->session->userdata('email');
$postArray = array(
'api_key' => 'my_api_key',
'email' => $email,
);
$curl_post_data = $postArray;
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
echo $curl_response;
echo $info;
Any advice would be greatly appreciated.
Upvotes: 0
Views: 3833
Reputation: 21463
your curl php code is sending the data in multipart/form-data
format, but as evident by their cli invocation example, their api wants the data in application/x-www-form-urlencoded
format.
as explained by the curl_setopt docs, when you give CURLOPT_POSTFIELDS an array, it will automatically be encoded to multipart/form-data
, if you give it a string, application/x-www-form-urlencoded
will automatically be assumed, and is what their curl cli invocation is using.
lucky for you, PHP has a dedicated function for encoding arrays to application/x-www-form-urlencoded
format, called http_build_query
, thus
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($curl_post_data));
will fix your issue of apparently sending empty parameters
.
also, if there is a problem setting any of your options, curl_setopt will return bool(false), which your code is completely ignoring, and would go unnoticed, you should fix that, consider using an error-catching setopt wrapper, like
function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
$ret=curl_setopt($ch,$option,$value);
if($ret!==true){
//option should be obvious by stack trace
throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . $ch .'. curl_error: '.curl_error($ch) );
}
return true;
}
Upvotes: 2