2011-12-16 68 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"); 
相關問題