file_get_contents 可讀取本地檔案或遠端 URL,但對帶端口號的網址(如 https://localhost:12345)常失敗。本文分析常見原因並提供解法。
CentOS/RHEL 系統預設啟用 SELinux,會限制 HTTPD 發起非標準端口連線。
setenforce 0
編輯 /etc/selinux/config:
SELINUX=disabled
重啟伺服器生效。
檢查 php.ini:
allow_url_fopen = On
修改後重啟 PHP-FPM/Apache。
若無權限修改上述設定,改用 cURL 更靈活且支援端口:
function curl_get($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
echo curl_get('https://localhost:12345');
allow_url_fopen = On。getenforce)。