You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP调用函数获取URL内容遭连接拒绝,浏览器访问正常求助

解决PHP中file_get_contents连接被拒绝的问题

你遇到的这个Connection refused错误很常见,通常是服务器端或者PHP配置层面的限制导致的。先梳理下你的测试场景:

你的测试代码

include_once("html_parser/simple_html_dom.php"); 
$html=file_get_html("http://82.77.18.164:8080/Iphone/get_puncte.php"); 
print_r($html); 
echo file_get_contents("http://82.77.18.164:8080/Iphone/get_puncte.php"); 
echo stream_get_contents(fopen('http://82.77.18.164:8080/Iphone/get_puncte.php', "r")); 

报错信息

PHP Warning: file_get_contents(http://82.77.18.164:8080/Iphone/get_puncte.php): failed to open stream: Connection refused;PHP Warning: stream_get_contents() expects parameter 1 to be resource, boolean given in /home/xxxxx/public_html/test.php on line 9


具体解决方案

1. 检查服务器防火墙/安全组规则

既然浏览器能正常访问,但PHP脚本不行,大概率是你的服务器防火墙或者主机商的安全组阻止了出站请求到8080端口:

  • 联系主机提供商,确认是否允许服务器向外发起8080端口的请求
  • 如果是自己管理的服务器,手动添加防火墙规则:比如Ubuntu/Debian用ufw allow out 8080/tcp,CentOS/RHEL用firewall-cmd --add-port=8080/tcp --permanent,添加后重启防火墙服务

2. 确认PHP的allow_url_fopen配置是否开启

file_get_contents访问远程URL需要allow_url_fopen设置为On:

  • 创建一个phpinfo.php文件,内容为<?php phpinfo(); ?>,访问后查找allow_url_fopen项
  • 如果是关闭状态,修改php.ini文件(或主机面板的PHP设置),将allow_url_fopen = On,然后重启PHP服务

3. 改用cURL替代file_get_contents

cURL通常比file_get_contents更稳定,且不受allow_url_fopen限制,试试这段代码:

$ch = curl_init("http://82.77.18.164:8080/Iphone/get_puncte.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 设置超时时间,避免无限等待
$response = curl_exec($ch);

if(curl_errno($ch)){
    echo "cURL Error: " . curl_error($ch);
} else {
    print_r($response);
}
curl_close($ch);

如果cURL报错,会返回更详细的错误信息,帮助精准定位问题。

4. 模拟浏览器请求头绕过访问限制

有些服务器会通过User-Agent判断请求来源,阻止非浏览器的请求,你可以手动添加浏览器的请求头:

  • 用file_get_contents的话,通过上下文参数添加:
$opts = [
    'http' => [
        'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n"
    ]
];
$context = stream_context_create($opts);
$content = file_get_contents("http://82.77.18.164:8080/Iphone/get_puncte.php", false, $context);
print_r($content);
  • 用cURL的话,添加这行配置:
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");

5. 验证服务器网络连通性

登录你的服务器,用命令行测试能否连接目标地址:

curl http://82.77.18.164:8080/Iphone/get_puncte.php

或者

telnet 82.77.18.164 8080

如果命令行也连接失败,说明是网络层面的问题,需要排查服务器的出站网络、路由,或者确认目标服务器的8080端口是否对服务器IP开放(浏览器能访问可能是因为本地网络和服务器网络的访问权限不同)。


内容的提问来源于stack exchange,提问作者PixelArtie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:17:14