當 file_get_contents() 獲取遠程內容返回空值或報錯時,通常是因為服務器禁用了 allow_url_fopen。本文提供從排查到替代的完整解決方案。
file_get_contents() 和 fopen() 依賴 allow_url_fopen = On。虛擬主機常關閉此選項,導致無法打開遠程文件。關鍵點:function_exists('file_get_contents') 返回 true 並不代表能訪問遠程 URL。
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, 'https://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
// ❌ 僅判斷函數是否存在
if (function_exists('file_get_contents')) {
$file_contents = @file_get_contents($url);
} else {
// 使用 cURL
}
// ✅ 判斷函數存在且獲取內容非空
if (function_exists('file_get_contents')) {
$file_contents = @file_get_contents($url);
}
if ($file_contents === '') { // 關鍵:檢查內容是否為空
$ch = curl_init();
$timeout = 30;
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);
}
function file_get_content($url) {
if (function_exists('file_get_contents')) {
$file_contents = @file_get_contents($url);
}
if ($file_contents === '') {
$ch = curl_init();
$timeout = 30;
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;
}
// 使用示例
echo file_get_content('https://www.example.com');
若主機商同時禁用
allow_url_fopen和 cURL 擴展,建議更換服務商。網絡請求是現代 Web 應用的基礎能力,不應受限於此。