部分主機商關閉 allow_url_fopen 選項,導致 file_get_contents() 無法讀取遠端 URL。此時可改用 cURL 擴展達成相同功能。
<?php
$file_contents = file_get_contents('https://www.ccvita.com/');
echo $file_contents;
?>
<?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 原始寫法作為最後備援。