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

PHP failed to open stream: HTTP request failed 完美解決方案

     編輯:PHP 綜合知識

錯誤訊息

Warning: readfile(https://example.com/logo.gif) [function.readfile]: failed to open stream: HTTP request failed!

常見原因與解決

  1. allow_url_fopen 未開啟
    ; php.ini
    allow_url_fopen = On
    修改後重啟 Web 服務。
  2. User-Agent 被遠端伺服器擋下 PHP 預設 User-Agent 為 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');
  3. 防火牆/反代/反爬蟲機制 遠端可能檢查 Referer、Cookie、IP 信譽等。

終極方案:改用 cURL

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 vs file_get_contents vs cURL 效能比較

特性fopen / file_get_contentscURL
DNS 快取無(每請求重新查詢)有(自動快取)
重導向處理需 allow_url_fopen 且 follow_location內建 CURLOPT_FOLLOWLOCATION
Post/檔案上傳困難原生支援
Cookie/Session 維持手動處理CURLOPT_COOKIEJAR/FILE
Proxy 支援無完整支援
效能(同域名多請求)較差優(DNS 快取、Keep-Alive)

結論:抓取遠端資源優先使用 cURL,穩定且功能完整。

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