跳到主要内容

PHP file_get_contents(): SSL operation failed with code 1 —— CA 证书与证书链完整排查指南

一、错误现场:三条 Warning 其实是同一件事

典型完整报错如下(PHP 7.x / 8.x 输出格式一致):

PHP Warning:  file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed in /var/www/app/fetch.php on line 12

PHP Warning:  file_get_contents(): Failed to enable crypto in /var/www/app/fetch.php on line 12

PHP Warning:  file_get_contents(https://api.example.com/v1/ping): failed to open stream: operation failed in /var/www/app/fetch.php on line 12

三条 Warning 分别来自 TLS 握手、加密流初始化、流打开三个阶段。只需要看第一条里 OpenSSL Error messages: 后面的内容,其余两条都是连带产物。函数返回 false,不会抛异常(除非你把 Warning 转成了 ErrorException)。

在 OpenSSL 3.x(PHP 8.1+ 常见)上,第二行会变成:

error:0A000086:SSL routines::certificate verify failed

错误码前缀变了,含义完全一样,别被网上的老帖子带偏。

二、code 1 到底是什么意思

code 1 不是证书错误码,而是 SSL_get_error() 的返回值:1 = SSL_ERROR_SSL,意思是“握手期间发生了协议层错误”,属于笼统分类。真正的诊断信息在紧随其后的 OpenSSL 错误队列里。

所以排查顺序永远是:先读 OpenSSL 那一行,再判断是本地 CA 问题还是远端证书链问题。实践中 90% 的情况落在两类:

  • 本地没有可用的 CA 证书包:PHP 编译时未指定默认路径、容器镜像没装 ca-certificates、openssl.cafile 指向了不存在或空的文件。对应 X509 校验码 20 (unable to get local issuer certificate)。
  • 远端证书链不完整:服务器只下发了叶子证书,没带中间证书。浏览器能打开是因为浏览器会走 AIA 抓取并缓存中间证书,而 PHP 的 OpenSSL 流默认不做 AIA fetching。对应校验码 2 / 21。

还有两类低频但真实存在的原因:自签名/内网 CA(校验码 18/19)、证书过期或系统时间漂移(校验码 9/10)。

三、三步定位:本地缺 CA 还是远端链不全

第一步:看 PHP 认为 CA 在哪

php -r 'print_r(openssl_get_cert_locations());'
php -i | grep -Ei 'openssl.cafile|openssl.capath|curl.cainfo'
php --ini

输出里 [ini_cafile] 为空,说明 php.ini 根本没配;default_cert_file 指向的路径如果不存在,就是本地缺 CA。注意 CLI 与 FPM 读的是不同的 php.ini:

php-fpm8.2 -i | grep 'Loaded Configuration File'

第二步:确认文件真实存在、非空、可读

ls -l /etc/ssl/certs/ca-certificates.crt
grep -c 'BEGIN CERTIFICATE' /etc/ssl/certs/ca-certificates.crt
sudo -u www-data test -r /etc/ssl/certs/ca-certificates.crt && echo readable

第三步:用 openssl 直接连一次,区分本地与远端

openssl s_client -connect api.example.com:443 -servername api.example.com 
  -CAfile /etc/ssl/certs/ca-certificates.crt -showcerts </dev/null

看结尾的 Verify return code:

  • 这里是 0 (ok),而 PHP 仍报错 → 问题在 PHP 配置(CA 路径、权限、读错了 php.ini)。
  • 这里也失败 → 问题在远端证书链或证书本身,PHP 只是受害者。

四、方案 A:在 php.ini 里指定 CA 包(最直接)

编辑 CLI 与 FPM 实际加载的那个 php.ini,加入:

openssl.cafile = /etc/ssl/certs/ca-certificates.crt
openssl.capath = /etc/ssl/certs
curl.cainfo    = /etc/ssl/certs/ca-certificates.crt

几个必须知道的细节:

  • openssl.cafile 影响 file_get_contents、fopen、stream_socket_client 等所有走 PHP openssl 流的函数;curl.cainfo 只影响 cURL 扩展,两者要分别配。
  • 都不能用 ini_set() 运行时修改:openssl.cafile 是 PHP_INI_PERDIR(FPM 场景可用 .user.ini),curl.cainfo 是 PHP_INI_SYSTEM(.user.ini 也无效)。
  • 路径必须是绝对路径,且 www-data / nginx 用户可读;相对路径会按进程工作目录解析,基本等于踩坑。

重载并验证:

sudo systemctl reload php8.2-fpm
php -r 'var_dump(file_get_contents('https://www.baidu.com') !== false);'

如果出现 Unable to set verify locations,说明 cafile 路径写错了或文件为空。

五、方案 B:更新并持续维护 CA 证书包

系统 CA 包过旧时(例如新根证书未被收录),也会出现同样的报错。Debian / Ubuntu:

sudo apt-get install -y ca-certificates
sudo update-ca-certificates

RHEL / CentOS / Rocky:

sudo yum install -y ca-certificates
sudo update-ca-trust extract

Alpine / 容器镜像:

apk add --no-cache ca-certificates && update-ca-certificates

如果系统包太旧、或你希望与 Mozilla 根证书同步,直接用 curl 官方维护的 cacert.pem:

sudo curl -fsSL https://curl.se/ca/cacert.pem -o /etc/ssl/certs/cacert.pem
sudo chmod 644 /etc/ssl/certs/cacert.pem
grep -c 'BEGIN CERTIFICATE' /etc/ssl/certs/cacert.pem

然后把 php.ini 的 openssl.cafile / curl.cainfo 指向这个文件。注意:Debian 系把文件丢进 /usr/local/share/ca-certificates/ 时,扩展名必须是 .crt,否则 update-ca-certificates 不会收录。

自动更新脚本(cacert.pem 更新频率很低,每月一次足够):

#!/bin/sh
# /etc/cron.monthly/update-cacert
curl -fsSL https://curl.se/ca/cacert.pem -o /etc/ssl/certs/cacert.pem.new 
  && grep -q 'BEGIN CERTIFICATE' /etc/ssl/certs/cacert.pem.new 
  && mv /etc/ssl/certs/cacert.pem.new /etc/ssl/certs/cacert.pem

先下载到临时文件、校验非空、再原子替换,可以避免下载失败时把可用的 CA 包清空。

六、方案 C:远端证书链不完整的排查与修复

先确认链上到底下发了几张证书:

openssl s_client -connect api.example.com:443 -servername api.example.com -showcerts </dev/null 2>/dev/null 
  | grep -E '^ *[0-9]+ s:|^ *i:'

正常应该有 2~3 张(叶子证书 + 中间证书)。只出现 1 个 s:,基本可以判定链不完整。也可以用一条命令列出全部证书主题:

openssl s_client -showcerts -connect api.example.com:443 </dev/null 2>/dev/null 
  | openssl crl2pkcs7 -nocrl -certfile - | openssl pkcs7 -print_certs -noout

把链下载下来本地验证,能复现问题才算定位准确:

openssl verify -CAfile /etc/ssl/certs/ca-certificates.crt -untrusted chain.pem leaf.pem

修复要在服务端做,不要在客户端关校验:

  • Nginx:ssl_certificate 必须指向 fullchain.pem(叶子证书在前,中间证书在后),而不是 cert.pem。
  • Apache 2.4.8+:SSLCertificateFile 直接给 fullchain;老版本用 SSLCertificateChainFile。
  • Let’s Encrypt / certbot:用 fullchain.pem;cert.pem 只是叶子证书。

如果你控制不了对端(第三方 API),可以在该请求的 stream context 里用 cafile 指定一个补入中间证书的 bundle,但这只是权宜之计,优先推动对方修复。

七、方案对比与代码层兜底

方案 生效范围 生效方式 适用场景 注意
openssl.cafile(php.ini) 全局,所有 PHP openssl 流 改 php.ini 后 reload php-fpm 服务器统一修复,首选 PHP_INI_PERDIR,ini_set() 无效
curl.cainfo(php.ini) 仅 cURL 扩展 同上 项目用 cURL 而非 file_get_contents PHP_INI_SYSTEM,.user.ini 也无效
stream context 的 ssl.cafile 单次请求 代码内传入 个别主机需要特殊 CA 要改代码,容易散落各处
系统 CA + update-ca-certificates 系统级(curl、wget、openssl,PHP 未显式配置时) 装包/更新后执行命令 根证书过旧、容器缺包 PHP 显式配了 cafile 则不受影响
SSL_CERT_FILE 环境变量 进程级 FPM pool 的 env[] 或 systemd 不想改 php.ini 的容器部署 需确认 OpenSSL 编译时启用了该变量
verify_peer => false 单次请求 代码内传入 不推荐 失去中间人防护,安全扫描高危

代码层兜底(只影响单次请求,适合特殊 CA 场景):

<?php
$ctx = stream_context_create([
    'ssl' => [
        'verify_peer'      => true,
        'verify_peer_name' => true,
        'cafile'           => '/etc/ssl/certs/ca-certificates.crt',
        'SNI_enabled'      => true,
        'peer_name'        => 'api.example.com',
    ],
]);
$body = file_get_contents('https://api.example.com/v1/ping', false, $ctx);

换成 cURL 扩展时,注意它读的是 curl.cainfo,也可以用 CURLOPT_CAINFO 单次覆盖:

<?php
$ch = curl_init('https://api.example.com/v1/ping');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CAINFO         => '/etc/ssl/certs/ca-certificates.crt',
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
]);
$body = curl_exec($ch);
if ($body === false) {
    error_log('curl error: ' . curl_error($ch));
}
curl_close($ch);

不要用 verify_peer => false 来“解决”问题:它把 TLS 的信任模型整个关掉,中间人可以直接解密和篡改请求,安全扫描会直接判定高危。真要绕过,也应只针对单个已知主机,并写明原因和到期时间。

八、排查手册:真实报错对照表

报错片段 含义 处理动作
error:1416F086 ... certificate verify failed(OpenSSL 1.1.1)
error:0A000086 ... certificate verify failed(OpenSSL 3.x)
证书校验失败的总类,具体原因看 verify code 执行 openssl s_client 看 Verify return code
Verify return code: 20 (unable to get local issuer certificate) 本地找不到签发者证书 配 openssl.cafile 或更新系统 CA
Verify return code: 2 (unable to get issuer certificate) 远端链缺中间证书 服务端改用 fullchain
Verify return code: 21 (unable to verify the first certificate) 叶子证书无法链到根 同上
self-signed certificate in certificate chain(18/19) 链里有自签名证书 内网自建 CA 需显式信任,或换受信任证书
certificate has expired(10) 证书过期 续期,同时检查系统时间
Unable to set verify locations cafile / capath 路径不可用 检查路径、权限、文件是否为空
Failed to enable crypto 握手失败的连带报错 忽略,看第一条
Peer certificate CN=... did not match expected CN=... 主机名不匹配 用正确域名访问,或显式设置 peer_name
curl: (60) SSL certificate problem: unable to get local issuer certificate cURL 侧同样缺 CA 配 curl.cainfo 或 CURLOPT_CAINFO

两个容易踩的坑:

  • 时间不同步:容器或 VM 时钟漂移会报 certificate is not yet valid / has expired,用 timedatectl 或 chronyc tracking 查一下。
  • 直连 IP:URL 里写 IP 会导致主机名校验失败,同时也拿不到正确的 SNI,务必用域名。

九、FAQ

为什么浏览器和 curl 都正常,只有 PHP 报错?

curl 命令行用的是系统 CA(/etc/ssl/certs),浏览器有自己的根证书库并会 AIA 抓取中间证书;PHP 用的是 openssl.cafile 指定的那个文件,三者互不相干。用 openssl_get_cert_locations() 看 PHP 实际用哪个文件,永远是排查的第一步。

code 1 和 Verify return code 20 是什么关系?

没有关系。code 1 是 SSL_get_error() 返回的 SSL_ERROR_SSL,属于握手阶段错误的笼统分类;20 是 X509 证书校验的具体原因(unable to get local issuer certificate)。前者只会告诉你“握手挂了”,后者才告诉你“为什么挂”。

改了 php.ini 为什么没生效?

最常见原因是改错了文件:CLI 用 php --ini,FPM 用 php-fpm8.2 -i | grep 'Loaded Configuration File',两者经常不是同一个。其次是忘了 reload php-fpm,或者只 reload 了 nginx。第三是 openssl.cafile 指向的文件不存在、为空、或 www-data 读不到。

能不能直接用 verify_peer => false?

技术上可以,工程上不建议。它关掉的是整条信任链验证,攻击者拿到任意证书就能冒充目标站点,中间人可完整读取和篡改请求内容(包括 API Key、Token)。如果确实面对内网自签名服务,正确做法是把该 CA 证书加入信任库,或在该请求的 cafile 里单独指定。

cacert.pem 需要多久更新一次?

根证书变动非常缓慢,半年到一年更新一次都够用;设成每月自动拉取更省心。真正需要及时更新的是系统 ca-certificates 包,尤其是新根证书上线后的过渡期。

PHP 8.3 / 8.4 还会出现这个报错吗?

会。这条报错的成因在 OpenSSL 和证书链,与 PHP 版本无关,PHP 8.x 只是把 OpenSSL 错误码前缀换成了 3.x 格式(0A000086)。排查方法和修复方式完全一致。