PHP - file get contents using CURL [duplicate] PHP - file get contents using CURL [duplicate] curl curl

PHP - file get contents using CURL [duplicate]


With curl, it's often a good idea to use curl_getinfo to obtain additional information about your curl connection before closing it. In your case, the NULL/FALSE/empty result could be due to a number of reasons and inspecting the curl info might help you find more detail. Here's a modified version of your function that uses this function to obtain additional information. You might consider writing print_r($info, TRUE) to a log file or something. It might be empty because the server response is empty. It might be false because the url cannot be reached from your server due to firewall issues. It might be returning an http_code that is 404 NOT FOUND or 5XX.

function file_get_contents_curl($url) {    $ch = curl_init();    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);    curl_setopt($ch, CURLOPT_HEADER, 0);    curl_setopt($ch, CURLOPT_ENCODING, 0);    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);    curl_setopt($ch, CURLOPT_TIMEOUT, 30);    curl_setopt($ch, CURLOPT_CUSTOMREQUEST , "GET");    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);    curl_setopt($ch, CURLOPT_URL, $url);    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));    $data = curl_exec($ch);    $info = curl_getinfo($ch);    if(curl_errno($ch)) {        throw new Exception('Curl error: ' . curl_error($ch));    }    curl_close($ch);    if ($data === FALSE) {        throw new Exception("curl_exec returned FALSE. Info follows:\n" . print_r($info, TRUE));    }    return $data;}

EDIT: I added curl_errno checking too.