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

Linux下PHP7.4服务器调用file_get_contents()仅单个URL失败

特定URL调用file_get_contents()失败排查问题

问题背景

  • 仅调用特定URL时file_get_contents()失败,已拥有源服务器和请求服务器的完整权限
  • 请求服务器配置:allow_url_fopen = On,且能正常获取其他接口数据(如https://jsonplaceholder.typicode.com/todos/1)
  • 源服务器已设置Header set Access-Control-Allow-Origin "*",目标URL响应头也包含Access-Control-Allow-Origin: *,且其他服务器可通过AJAX正常获取该数据
  • 异常差异:http://test.tioray.com调用失败,http://test.web-dewd-test.co.uk调用正常;两台服务器PHP配置看似一致,且均能正常获取其他接口数据,AJAX调用目标源数据也无异常

测试代码

$dflURL = 'https://dataflexlink.tech/rest/plugin-info/';

$options = ['http' => [
        'timeout' => 5,
        'method' => 'GET',
        'header' => 'Content-type:application/json'
]];

$context  = stream_context_create($options);

$test = file_get_contents($dflURL,false,$context);

排查建议

1. 捕获明确错误信息

先在代码中添加错误捕获,定位具体失败原因:

error_reporting(E_ALL);
ini_set('display_errors', 1);

$test = file_get_contents($dflURL,false,$context);
if($test === false) {
    $error = error_get_last();
    var_dump($error);
}

也可通过stream_get_meta_data查看请求的响应元信息,确认是否返回HTTP错误码。

2. 排查SSL证书验证差异

两台服务器的SSL信任配置可能存在差异,可先测试跳过证书验证(仅用于排查,生产环境禁止):

$options = ['http' => [
        'timeout' => 5,
        'method' => 'GET',
        'header' => 'Content-type:application/json'
    ],
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
];

若测试通过,说明问题出在证书信任链,需检查失败服务器的CA证书是否缺失或过期。

3. 对比服务器环境细节

不要仅看表面配置,重点检查:

  • 执行phpinfo(),对比openssl扩展版本、curl扩展状态
  • 检查服务器防火墙/安全组规则,是否限制了对目标域名的出站请求
  • 查看服务器hosts文件,是否存在目标域名的错误解析
  • 尝试在请求头中添加标准User-Agent,模拟浏览器请求:
'header' => [
    'Content-type:application/json',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]

4. 网络连通性测试

在失败的服务器上执行命令行测试:

  • curl -v https://dataflexlink.tech/rest/plugin-info/,查看请求过程中的错误提示
  • ping dataflexlink.tech和traceroute dataflexlink.tech,检查网络链路是否通畅
  • 查看服务器系统日志(如/var/log/apache2/error.log或/var/log/nginx/error.log),是否有相关请求错误记录

5. 模拟AJAX请求头

AJAX请求与PHP请求的头信息存在差异,尝试模拟AJAX的请求头:

$options = ['http' => [
        'timeout' => 5,
        'method' => 'GET',
        'header' => [
            'Content-type:application/json',
            'Accept: application/json, text/javascript, */*; q=0.01',
            'X-Requested-With: XMLHttpRequest'
        ]
]];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:35:13