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

线上环境file_get_contents()请求失败,localhost环境正常运行

解决file_get_contents() SSL读取错误(errno 56)的方案

可能的原因及修复步骤

  • 服务器SSL配置差异
    本地环境和线上服务器的OpenSSL版本、CA证书库可能不一致。可先通过临时禁用SSL验证测试(仅用于排查,生产环境不建议):

    $context = stream_context_create([
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ]
    ]);
    $pdfContent = file_get_contents('https://目标PDF地址', false, $context);
    

    如果测试有效,说明是CA证书问题,建议配置服务器正确的CA证书路径,比如Linux系统指向/etc/ssl/certs/ca-certificates.crt。

  • 服务器防火墙/安全组限制
    线上服务器可能被目标网站防火墙拦截,或自身防火墙限制了出站HTTPS请求。可在服务器终端用curl命令测试:

    curl -v https://目标PDF地址 -o test.pdf
    

    根据curl输出判断是否存在连接被拒绝、超时或SSL握手失败的情况,再联系服务商调整规则。

  • 模拟合规HTTP请求头
    Insomnia请求正常可能是因为它的请求头更符合目标网站要求,尝试在file_get_contents中模拟浏览器请求头:

    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            '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" .
                        "Accept: application/pdf\r\n" .
                        "Connection: keep-alive"
        ],
        'ssl' => [
            'verify_peer' => true,
            'verify_peer_name' => true
        ]
    ]);
    $pdfContent = file_get_contents('https://目标PDF地址', false, $context);
    
  • 替换为cURL实现
    file_get_contents对复杂HTTP/SSL场景支持有限,换成cURL通常能解决问题:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://目标PDF地址');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        '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',
        'Accept: application/pdf'
    ]);
    $pdfContent = curl_exec($ch);
    if(curl_errno($ch)){
        echo 'CURL错误:' . curl_error($ch);
    }
    curl_close($ch);
    
  • 指定SSL/TLS协议版本
    服务器可能不支持目标网站使用的SSL/TLS版本,可在上下文选项中明确允许的协议:

    $context = stream_context_create([
        'ssl' => [
            'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT
        ]
    ]);
    $pdfContent = file_get_contents('https://目标PDF地址', false, $context);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:01:21