Reputation: 373
I am working on this for 2 hours and just can't figure out what's wrong. I am making a cURL get request with just the URL (with parameters) and the response is expected to be some kind of access_token in JSON format but I am continually getting an error: the curl_exec()
function is returning false
. The URL is alright because directly pasting the prepared URL to the browser address bar gives the appropriate access_token. You may need to know that I am making a graph API (Facebook) request. Here is some code:
private function getAccessToken() {
$uri = $this->prepareTokenUri(); // getting the uri
echo "<strong>$uri</strong><br/>"; // printing the uri for debugging purpose
$this->setCurlToGet($uri); // explained below
$response = curl_exec($this->curl);
echo "<b>Here Goes Response</b>";
var_dump($response); // boolean false
$response = json_decode($response, true);
$this->token_expires = $response['expires_in'];
$this->token_type = $response['type'];
return $response['access_token'];
}
The function setCurlToGet()
just does the following:
// call this function only when making a GET request
private function setCurlToGet($url) {
$this->unsetCurl();
$this->curl = curl_init();
curl_setopt($this->curl, CURLOPT_URL, $url);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
return $this->curl;
}
and the unsetCurl()
method is as follows:
private function unsetCurl() {
if(!is_null($this->curl)) {
curl_close($this->curl);
$this->curl = null;
}
}
I have var_dumped() everything, the cURL resource variable ($this->curl
) and it is actually a curl resource variable. The call to curl_exec()
is returning false and I just can't figure out why. Again, I would like to repeat that there is nothing wrong with the URL because when the printed url (in the line echo "<strong>$uri</strong><br/>";
) is copied and pasted in browser's address bar, result is an access_token that I need.
In case you wanted to see the pattern of URI that prepareTokenUri()
is preparing:
https://graph.facebook.com/v2.3/oauth/access_token?client_id={my-appid}&redirect_uri={response-handler-script-uri}&client_secret={app-secret-code}&code={a-long-code}
Upvotes: 1
Views: 1100
Reputation: 5371
The quick fix:
Add these lines to your setCurlToGet
function in same area as other curl_setopt methods.
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, 0);
The only issue with this is that if someone is able to make dns go to their server, instead of facebook as expected from url, that you are not verifying that it is indeed facebook.
So if you are worried about that, the proper fix:
1) Download cacert.pem from https://curl.haxx.se/ca/cacert.pem
2) Add the following line to php.ini, with correct path of where you put the above file
curl.cainfo=/path/to/cacert.pem
3) Reload apache service
Upvotes: 2