首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

file_get_contents 被禁用時的替代方案:使用 cURL 獲取遠端網頁內容

     編輯:PHP 綜合知識

問題背景

部分主機商關閉 allow_url_fopen 選項,導致 file_get_contents() 無法讀取遠端 URL。此時可改用 cURL 擴展達成相同功能。

兩種寫法對比

file_get_contents 版本

<?php
$file_contents = file_get_contents('https://www.ccvita.com/');
echo $file_contents;
?>

cURL 版本

<?php
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, 'https://www.ccvita.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>

通用封裝函數

利用 function_exists() 判斷可用函數,自動切換:

<?php
function vita_get_url_content($url) {
    if (function_exists('file_get_contents')) {
        $file_contents = file_get_contents($url);
    } else {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
    }
    return $file_contents;
}
?>

注意事項

若主機商同時禁用 file_get_contents 與 cURL,上述函數仍會報錯。生產環境建議再加入 fopen + stream_get_contents 或 Socket 原始寫法作為最後備援。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved