How to use CURL instead of file_get_contents?

Morteza picture Morteza · Dec 16, 2011 · Viewed 79.9k times · Source

I use file_get_contents function to get and show external links on my specific page.

In my local file everything is okay, but my server doesn't support the file_get_contents function, so I tried to use cURL with the below code:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

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

    return $data;
}

 echo file_get_contents_curl('http://google.com');

But it returns a blank page. What is wrong?

Answer

lord_viper picture lord_viper · Dec 17, 2011

try this:

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_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       

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

    return $data;
}