2011-12-16 50 views
28

我使用file_get_contents函数来获取并显示特定页面上的外部链接。如何使用CURL而不是file_get_contents?

在我的本地文件一切都没有问题,但我的服务器不支持file_get_contents功能,所以我试图使用卷曲与下面的代码:

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'); 

但它返回一个空白页。哪里不对?

+3

什么是[curl_error](http://php.net/manual/en/function.curl-error.php)说? – 2011-12-16 22:21:16

+2

你的编码工作,也许卷曲不安装?在phpinfo() – malletjo 2011-12-16 22:22:51

+3

中检查你没有做错误检查,然后想知道为什么没有错误出现。这是......不明智的。 – 2011-12-16 22:23:25

回答

68

试试这个:

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; 
} 
8

这应该工作

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); 
1

//你可以试试这个。它应该工作正常。

function curl_tt($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); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 3);  
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
$data = curl_exec($ch); 
curl_close($ch); 

return $data; 
} 
echo curl_tt("https://google.com"); 
相关问题