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

PHP fopen 無法開啟遠端網址的解決:allow_url_fopen、hosts 檔案與 stream wrapper

     編輯:PHP 相關知識

fopen、getimagesize、include 等函式若要開啟 HTTP/HTTPS URL,需滿足三個條件。

條件一:php.ini 開啟 allow_url_fopen

allow_url_fopen = On
allow_url_include = On  ; 若需 include/require 遠端檔案

修改後重啟 PHP-FPM/Apache。

條件二:本地測試環境 localhost 解析問題

Windows 下 fopen('https://localhost/...') 常卡住逾時,換成 127.0.0.1 即正常。原因是 hosts 檔案未生效。

修正 hosts

編輯 C:\Windows\System32\drivers\etc\hosts,確保有:

127.0.0.1   localhost

移除前方 # 號,存檔即時生效。

條件三:SELinux/Firewall 阻擋(Linux)

  • 臨時關閉 SELinux:setenforce 0。
  • 永久關閉:/etc/selinux/config 設 SELINUX=disabled 重啟。
  • 防火牆放行 HTTP/HTTPS 輸出連線。

進階:使用 stream wrapper 處理 GZIP/HTTPS

$content = file_get_contents("compress.zlib://https://example.com");

或改用 cURL 完整支援協議、驗證、代理等。

傳參技巧:include 遠端檔案帶參數

<?php include 'https://domain.com/inc.php?foo=1&bar=2'; ?>
// inc.php 內可直接用 $_GET['foo']、$_GET['bar']

排查清單

  1. allow_url_fopen = On?
  2. 本地用 127.0.0.1 替代 localhost?
  3. 防火牆/SELinux 是否阻擋?
  4. 目標 URL 直接瀏覽器訪問是否正常?
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved