Warning: readfile(https://example.com/logo.gif) [function.readfile]: failed to open stream: HTTP request failed!
; php.ini
allow_url_fopen = On
修改後重啟 Web 服務。PHP,許多網站封鎖。需偽裝為瀏覽器:
; php.ini
user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
或程式碼中設定:
ini_set('user_agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');cURL 功能完整、支援 Cookie、SSL、Proxy、重導向、超時控制,且不受 allow_url_fopen 限制。
<?php
function fetchUrl($url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false, // 僅測試用,生產請驗證憑證
]);
$content = curl_exec($ch);
if (curl_errno($ch)) {
error_log("cURL Error: " . curl_error($ch));
return false;
}
curl_close($ch);
return $content;
}
echo fetchUrl('https://example.com/logo.gif');
| 特性 | fopen / file_get_contents | cURL |
|---|---|---|
| DNS 快取 | 無(每請求重新查詢) | 有(自動快取) |
| 重導向處理 | 需 allow_url_fopen 且 follow_location | 內建 CURLOPT_FOLLOWLOCATION |
| Post/檔案上傳 | 困難 | 原生支援 |
| Cookie/Session 維持 | 手動處理 | CURLOPT_COOKIEJAR/FILE |
| Proxy 支援 | 無 | 完整支援 |
| 效能(同域名多請求) | 較差 | 優(DNS 快取、Keep-Alive) |
結論:抓取遠端資源優先使用 cURL,穩定且功能完整。