跳到主要内容

PHP: file_get_contents(): SSL operation failed with code 1

What "SSL operation failed with code 1" actually means

file_get_contents() on an https:// URL goes through PHP’s OpenSSL stream wrapper. Before a single byte of body is returned, OpenSSL must build a chain from the server’s leaf certificate up to a root it trusts. code 1 is PHP’s own generic stream-wrapper failure code — it tells you nothing. The real reason is printed after OpenSSL Error messages:, and the warning is usually followed by two more lines:

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/status): failed to open stream: operation failed in /var/www/app/fetch.php on line 12

There are only two families of cause:

  • Local — PHP has no CA bundle configured, points at a path that does not exist, cannot read the file as the FPM user, or uses a bundle too old to contain the root that issued the server certificate.
  • Remote — the server sends an incomplete chain (missing intermediate), its certificate expired, the hostname does not match, or a TLS-inspecting proxy is re-signing traffic with a private CA you do not trust.

Diagnose which one before changing anything.

Step 1 — Two-minute triage: local store or remote chain?

Ask PHP where it thinks its trust store lives:

php -r 'print_r(openssl_get_cert_locations());'

A broken stock build typically reports paths that do not exist on the machine:

Array
(
    [default_cert_file] => /usr/local/ssl/cert.pem
    [default_cert_file_env] => SSL_CERT_FILE
    [default_cert_dir] => /usr/local/ssl/certs
    [default_cert_dir_env] => SSL_CERT_DIR
    [default_private_dir] => /usr/local/ssl/private
    [default_cert_file_env] => SSL_CERT_FILE
)

Then confirm what the running SAPI actually loaded and reproduce the failure:

php --ini
php -i | grep -E 'openssl.cafile|openssl.capath|curl.cainfo|Loaded Configuration'
php -r 'var_dump(file_get_contents("https://www.example.com") !== false);'

Now test the same host with OpenSSL directly, using the OS trust store:

openssl s_client -connect www.example.com:443 -servername www.example.com 
  -CAfile /etc/ssl/certs/ca-certificates.crt </dev/null 2>/dev/null | grep 'Verify return code'

Verify return code: 0 (ok) means the chain is fine and the fault is entirely on the PHP side — go to Step 2. Codes 10, 20 or 21 point at the remote chain or a clock problem — jump to the remote-chain section.

Step 2 — Point PHP at a CA bundle in php.ini

Find the bundle your distribution already maintains:

  • Debian / Ubuntu: /etc/ssl/certs/ca-certificates.crt
  • RHEL / CentOS / Alma / Rocky: /etc/pki/tls/certs/ca-bundle.crt
  • Alpine: /etc/ssl/cert.pem (after apk add ca-certificates)
  • macOS with Homebrew: /opt/homebrew/etc/openssl@3/cert.pem
  • Windows: C:phpextrassslcacert.pem

Add three lines to the php.ini used by the web SAPI:

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

openssl.cafile is PHP_INI_PERDIR and curl.cainfo is PHP_INI_SYSTEM, so neither can be changed with ini_set() at runtime. This is the single most common reason "the fix didn’t work".

Reload and verify as the web user, not as root:

sudo systemctl reload php8.2-fpm     # or: sudo systemctl restart apache2
php -i | grep -E 'openssl.cafile|curl.cainfo'
sudo -u www-data php -r 'var_dump(file_get_contents("https://www.example.com") !== false);'

That last command matters: FPM runs as www-data, nginx or apache, and a bundle you dropped in /root is unreadable to it even though the CLI test passes.

Step 3 — Ship your own cacert.pem (containers and shared hosting)

The OS bundle can be months stale, and on shared hosting you often cannot edit php.ini. curl.se publishes a maintained Mozilla-derived bundle with a published checksum:

sudo curl -fsSLo /etc/ssl/certs/cacert.pem https://curl.se/ca/cacert.pem
sudo chmod 644 /etc/ssl/certs/cacert.pem
curl -fsSLo /tmp/cacert.pem.sha256 https://curl.se/ca/cacert.pem.sha256
cd /etc/ssl/certs && sha256sum -c /tmp/cacert.pem.sha256

Set openssl.cafile = /etc/ssl/certs/cacert.pem, reload, then keep it fresh with a monthly job:

# /etc/cron.monthly/update-cacert
#!/bin/sh
set -e
curl -fsSLo /etc/ssl/certs/cacert.pem.new https://curl.se/ca/cacert.pem
mv /etc/ssl/certs/cacert.pem.new /etc/ssl/certs/cacert.pem
chmod 644 /etc/ssl/certs/cacert.pem
systemctl reload php8.2-fpm || true

In Docker, bake it in so runtime never depends on egress:

FROM php:8.3-fpm
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates 
 && update-ca-certificates 
 && printf 'openssl.cafile=/etc/ssl/certs/ca-certificates.crtncurl.cainfo=/etc/ssl/certs/ca-certificates.crtn' 
    > /usr/local/etc/php/conf.d/ssl-ca.ini

Do not concatenate several bundles together: duplicate certificates are a commonly reported trigger for X509_STORE_add_cert:cert already in hash table. Use one clean file.

Step 4 — Per-request override with a stream context

When php.ini is out of reach, pass the trust store to the individual call:

<?php
$ctx = stream_context_create([
    'ssl' => [
        'cafile'           => '/etc/ssl/certs/cacert.pem',
        'verify_peer'      => true,
        'verify_peer_name' => true,
        'SNI_enabled'      => true,
        'peer_name'        => 'api.example.com', // required when calling by IP
    ],
]);

$body = @file_get_contents('https://api.example.com/v1/status', false, $ctx);
if ($body === false) {
    throw new RuntimeException('HTTP fetch failed: ' . error_get_last()['message']);
}

For cURL the equivalent is CURLOPT_CAINFO; for Guzzle, ['verify' => '/etc/ssl/certs/cacert.pem'] on the client or request.

Comparison: which fix should you use?

Approach Scope Covers file_get_contents Covers cURL / Guzzle Runtime-settable Use when
openssl.cafile in php.ini Whole PHP process Yes No No (PHP_INI_PERDIR) You control php.ini — the default fix
curl.cainfo in php.ini Whole PHP process No Yes No (PHP_INI_SYSTEM) cURL clients, Composer, Guzzle
openssl.capath in php.ini Whole PHP process Yes No No You keep hashed certificates in a directory
Stream context ssl.cafile Single call Yes No Yes Shared hosting, no ini access
CURLOPT_CAINFO / Guzzle verify Single client No Yes Yes Per-service pinning
SSL_CERT_FILE env var Process environment Sometimes Sometimes Yes Containers; build-dependent, verify it took effect
verify_peer => false — Yes Yes Yes Never in production

Troubleshooting: real messages and what they mean

Message Meaning Fix
error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed No usable CA bundle, wrong path, or unreadable file (OpenSSL 1.1 naming) Set openssl.cafile to an existing, readable bundle and reload FPM
error:0A000086:SSL routines::certificate verify failed Same failure, OpenSSL 3 renamed the routine Same fix — do not be misled by the different prefix
file_get_contents(): Failed to enable crypto Generic wrapper message; the real cause is the OpenSSL line printed above it Read upward in the log, usually a typo in the cafile path
file_get_contents(https://...): failed to open stream: operation failed Wrapper-level failure with no detail of its own Enable log_errors and read the two preceding warnings
error:0B07C065:x509 certificate routines:X509_STORE_add_cert:cert already in hash table Duplicate certificates inside the bundle (concatenated files) Use a single clean cacert.pem from curl.se
Peer certificate CN='api.example.com' did not match expected CN='10.0.0.5' You called an IP address; the certificate is for a hostname Call by hostname, or set ssl.peer_name / CURLOPT_SSL_VERIFYHOST semantics via the hostname
certificate has expired Leaf or intermediate is out of validity openssl s_client -connect host:443 -servername host </dev/null 2>/dev/null | openssl x509 -noout -dates; also check date -u
unable to get local issuer certificate (from s_client) Server is not sending its intermediate certificate Fix the server chain, not your PHP config
SSL certificate problem: unable to get local issuer certificate (cURL) curl.cainfo not configured, or Guzzle verify points nowhere Set curl.cainfo or pass CURLOPT_CAINFO
failed to open stream: Permission denied on the bundle path FPM user cannot read the file sudo -u www-data head -1 /etc/ssl/certs/cacert.pem and fix mode/ownership
https:// wrapper is disabled in the server configuration by allow_url_fopen=0 Different problem entirely — the wrapper is switched off Enable allow_url_fopen or use cURL

When the remote chain is the problem

Dump the chain the server actually sends:

openssl s_client -connect api.example.com:443 -servername api.example.com -showcerts </dev/null

Read the tail of the output. Verify return code: 21 (unable to verify the first certificate) or 20 (unable to get local issuer certificate) means the intermediate is missing from the handshake. Count what was sent and inspect the leaf:

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

Then prove it is not your store by retesting with a known-good bundle:

openssl s_client -connect api.example.com:443 -servername api.example.com 
  -CAfile /etc/ssl/certs/cacert.pem </dev/null 2>&1 | grep 'Verify return code'

Also rule out three silent killers: a skewed system clock (timedatectl), a corporate TLS-inspection proxy whose private root CA must be appended to the bundle rather than verification being disabled, and SNI-strict front ends that serve a default certificate when -servername is omitted.

FAQ

Does ini_set('openssl.cafile', ...) work?
No. It is PHP_INI_PERDIR, so it must be set in php.ini, a conf.d/*.ini file, .htaccess or the vhost definition. Use a stream context for per-request control.
I edited php.ini and nothing changed — why?
CLI and FPM read different files. Check php --ini for CLI and php-fpm8.2 -i | grep 'Loaded Configuration' (or a phpinfo() page) for the web SAPI, then reload FPM. An opcache of the ini is not a thing, but a forgotten reload is.
Is verify_peer => false an acceptable workaround?
No. It disables authentication, so every request becomes trivially MITM-able, and the code path silently survives into production. Fix the bundle instead.
Why does it work on the command line but fail in the browser?
Different php.ini, a different user (file permissions on the bundle), or open_basedir blocking the bundle path.
Does this also fix Composer and Guzzle?
Composer ships its own bundle; if it still fails run composer config --global cafile /etc/ssl/certs/cacert.pem. Guzzle uses cURL, so curl.cainfo or a per-client verify option applies.
What about Windows?
PHP’s https:// wrapper does not use the Windows certificate store. Download cacert.pem and set openssl.cafile=C:phpextrassslcacert.pem plus curl.cainfo to the same file.
And Alpine-based containers?
apk add --no-cache ca-certificates && update-ca-certificates, then point openssl.cafile at /etc/ssl/cert.pem (or /etc/ssl/certs/ca-certificates.crt on newer images) and reload PHP.