在 PHP 開發中,抓取遠端網頁內容是常見需求。許多開發者習慣使用 file_get_contents(),但部分主機商為了安全考量會關閉 allow_url_fopen 選項,導致該函數無法獲取遠端資源。此時,cURL 擴展 便是最佳替代方案,功能更強大、穩定性更高。
<?php
$file_contents = file_get_contents('https://www.example.com');
echo $file_contents;
?>
<?php
$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);
echo $file_contents;
?>
為了兼容不同伺服器環境,可封裝一個智慧函數,優先使用 file_get_contents,不可用時自動回退至 cURL:
<?php
function vita_get_url_content($url) {
if (function_exists('file_get_contents') && ini_get('allow_url_fopen')) {
return file_get_contents($url);
}
if (function_exists('curl_init')) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
return false; // 兩者皆不可用
}
?>
若主機商同時禁用 file_get_contents(關閉 allow_url_fopen)與 cURL 擴展,上述函數將回傳 false。建議在專案部署前檢查伺服器環境,或採用更完善的 HTTP 客戶端庫(如 Guzzle)。
allow_url_fopen 設定,無法精細控制請求行為。