CURL PHP RESTful service always returns FALSE

I am having some difficulties POSTing an json API object that uses REST. I am new to using cURL, but I searched everything to try to find the answer to my problem, but came up with a short one. My cURL request always returns false. I know this is not even a message from my json object, because I still get a response from url. My code is below.

<?php //API KEY = APIUsername //API_CODE = APIPassword $API_Key = "some API key"; $API_Code = "some API code"; $API_email = " email@email.com "; $API_password = "ohhello"; $url = "http://someURL.com/rest.svc/blah"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); header('Content-type: application/json'); $authData = "{\"APIUsername\":\"$API_Key\",\"APIPassword\":\"$API_Code\",\"EmailAddress\":\"$API_email\",\"Password\":\"$API_password\"}"; curl_setopt($ch, CURLOPT_POSTFIELDS, $authData); //make the request $result = curl_exec($ch); $response = json_encode($result); echo $response; curl_close() ?> 

$ Response only returns false

Any thoughts?

+7
source share
1 answer

$response most likely incorrect because curl_exec() returns false (i.e., failure) in $result . Echo out curl_error($ch) (after calling curl_exec) to see the cURL error if this is a problem.

In another note, I think your CURLOPT_POSTFIELDS is in an invalid format. You are not passing a JSON string for this.

This parameter can be passed as a string with urlencoded, like 'para1 = val1 & para2 = val2 & ...' or as an array with the field name as the key and field data as the value.

- PHP documents for curl_setopt ()


Update

A quick way to avoid an SSL error is to add this option:

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

You get an SSL verification error because cURL, unlike browsers, does not have a preloaded list of trusted certificate authorities (CAs), so SSL certificates are not trusted by default. The quick fix is ​​to simply accept certificates without verification using the line above. The best solution is to manually add only the certificates or CA (s) that you want to accept. See this article on cURL and SSL for more information.

+24
source

All Articles