如何使用CURL而不是file_get_contents?

Mor*_*eza 34 php curl file-get-contents

我使用file_get_contents函数来获取和显示我的特定页面上的外部链接.

在我的本地文件中一切正常,但我的服务器不支持该file_get_contents功能,所以我尝试使用以下代码的cURL:

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');
Run Code Online (Sandbox Code Playgroud)

但它返回一个空白页面.怎么了?

lor*_*per 76

试试这个:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • Curl 返回空内容.. 我怎样才能避免这种情况? (2认同)

CLU*_*3SS 10

这应该工作

function curl_load($url){
    curl_setopt($ch=curl_init(), CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

$url = "http://www.google.com";
echo curl_load($url);
Run Code Online (Sandbox Code Playgroud)

  • 此代码的行为与file_get_contents完全不同.您的代码不会遵循重定向,file_get_contents会这样做. (2认同)