TLS and HTTPS

suggest change

TLS (Transport Layer Security) encrypts a connection and lets the client verify that it is talking to the right server. HTTPS is plain HTTP sent over a TLS connection.

PHP uses the OpenSSL library for TLS in two places:

Both verify server certificates by default. Most TLS problems in PHP come from a missing CA bundle, and the wrong fix is to turn verification off.

Making HTTPS requests with cURL

By default cURL verifies the certificate chain (CURLOPT_SSL_VERIFYPEER) and checks that the certificate matches the host name (CURLOPT_SSL_VERIFYHOST). You can also require a minimum TLS version:

<?php
$ch = curl_init('https://www.example.com/');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => true,   // default; never set to false in production
    CURLOPT_SSL_VERIFYHOST => 2,      // default; check the host name in the certificate
    CURLOPT_SSLVERSION     => CURL_SSLVERSION_TLSv1_2, // TLS 1.2 or newer
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT        => 30,
]);

$body = curl_exec($ch);
if ($body === false) {
    // e.g. "SSL certificate OpenSSL verify result: unable to get local issuer certificate (20)"
    // (older libcurl: "SSL certificate problem: unable to get local issuer certificate")
    throw new RuntimeException('Request failed: ' . curl_error($ch));
}

echo curl_getinfo($ch, CURLINFO_HTTP_CODE), "\n";
echo curl_getinfo($ch, CURLINFO_SCHEME), "\n"; // "https" (PHP 7.3+)

CURL_SSLVERSION_TLSv1_2 means "at least TLS 1.2", so TLS 1.3 is still negotiated when both sides support it.

There is no need to call curl_close(): since PHP 8.0 the handle is an object freed automatically, and curl_close() does nothing (it is deprecated in PHP 8.5).

Fixing "unable to get local issuer certificate"

This error means PHP cannot find the list of trusted root certificates (the CA bundle). This is common on Windows and in minimal Docker images. Fix it by pointing PHP at a CA bundle, for example the Mozilla bundle published by curl:

; php.ini
curl.cainfo   = "C:\php\extras\ssl\cacert.pem"
openssl.cafile = "C:\php\extras\ssl\cacert.pem"

curl.cainfo is used by cURL, openssl.cafile by streams. On Linux, installing the ca-certificates package usually solves it.

You can also set the bundle per request, which is useful for talking to servers that use a private (company) CA:

<?php
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/certs/internal-ca.pem');

To see which defaults PHP is using:

<?php
print_r(openssl_get_cert_locations());

Do not "fix" the error with CURLOPT_SSL_VERIFYPEER => false or verify_peer => false. That keeps the traffic encrypted but lets anyone on the network pretend to be the server, which makes the encryption worthless.

HTTPS with streams

file_get_contents() and fopen() support https:// URLs when the openssl extension is enabled. TLS options go into the ssl key of a stream context:

<?php
$context = stream_context_create([
    'ssl' => [
        'verify_peer'       => true,  // default
        'verify_peer_name'  => true,  // default
        'crypto_method'     => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
                             | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT, // PHP 7.4+
        'capture_peer_cert' => true,
    ],
    'http' => [
        'timeout' => 10,
    ],
]);

$html = file_get_contents('https://www.example.com/', false, $context);
if ($html === false) {
    throw new RuntimeException('Request failed');
}
echo strlen($html), " bytes\n";

Other useful ssl context options:

Option Meaning
cafile / capath CA bundle file / directory to trust
peer_name host name to verify against, if it differs from the URL host
allow_self_signed accept self-signed certificates (only with verify_peer still on, for testing)
local_cert, local_pk, passphrase client certificate and private key
peer_fingerprint pin the certificate by its hash, e.g. ['sha256' => '...']
ciphers OpenSSL cipher list

Inspecting the server certificate

With capture_peer_cert set, the certificate is stored in the context. The script below connects with stream_socket_client() and prints when a certificate expires, which is handy for monitoring:

<?php
function certificateInfo(string $host, int $port = 443): array
{
    $context = stream_context_create([
        'ssl' => [
            'capture_peer_cert' => true,
            'SNI_enabled'       => true,
            'peer_name'         => $host,
        ],
    ]);

    $client = stream_socket_client(
        "tls://$host:$port",
        $errno,
        $errstr,
        10,
        STREAM_CLIENT_CONNECT,
        $context
    );
    if ($client === false) {
        throw new RuntimeException("Cannot connect to $host:$port: $errstr ($errno)");
    }

    $params = stream_context_get_params($client);
    $cert = openssl_x509_parse($params['options']['ssl']['peer_certificate']);
    fclose($client);

    return $cert;
}

$cert = certificateInfo('www.php.net');
$expires = (new DateTimeImmutable())->setTimestamp($cert['validTo_time_t']);
$daysLeft = (new DateTimeImmutable())->diff($expires)->days;

echo 'Subject: ', $cert['subject']['CN'], "\n";
echo 'Issuer:  ', $cert['issuer']['O'] ?? $cert['issuer']['CN'], "\n";
echo 'Expires: ', $expires->format('Y-m-d'), " ($daysLeft days)\n";

With cURL, set CURLOPT_CERTINFO => true and read curl_getinfo($ch, CURLINFO_CERTINFO) after the request to get the whole chain.

Client certificates (mutual TLS)

Some APIs (banks, payment providers, internal services) require the client to present its own certificate:

<?php
$ch = curl_init('https://api.partner.example/v1/status');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSLCERT        => __DIR__ . '/certs/client.crt',
    CURLOPT_SSLKEY         => __DIR__ . '/certs/client.key',
    CURLOPT_SSLKEYPASSWD   => getenv('CLIENT_KEY_PASSWORD') ?: '',
    CURLOPT_CAINFO         => __DIR__ . '/certs/partner-ca.pem',
]);
$response = curl_exec($ch);

The streams equivalent uses local_cert, local_pk and passphrase in the ssl context.

Certificate pinning

Pinning restricts a connection to a specific public key, on top of normal verification. cURL accepts the SHA-256 hash of the public key:

<?php
// the hash is a placeholder; compute the real one from the server's public key
curl_setopt($ch, CURLOPT_PINNEDPUBLICKEY, 'sha256//YhKJKSzoTt2b5FP18fvpHo7fJYqQCjAa3HWY3tvRMwE=');

Pinning breaks when the server rotates its key, so only use it when you control both ends or the provider publishes its keys.

A minimal TLS server

stream_socket_server() with the tls:// scheme creates a TLS listener. For local testing create a self-signed certificate first:

openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
  -keyout server.key -out server.crt -subj "/CN=localhost"
<?php
$context = stream_context_create([
    'ssl' => [
        'local_cert'    => __DIR__ . '/server.crt',
        'local_pk'      => __DIR__ . '/server.key',
        'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER
                         | STREAM_CRYPTO_METHOD_TLSv1_3_SERVER,
    ],
]);

$server = stream_socket_server(
    'tls://127.0.0.1:8443',
    $errno,
    $errstr,
    STREAM_SERVER_BIND | STREAM_SERVER_LISTEN,
    $context
);
if ($server === false) {
    exit("Cannot start server: $errstr ($errno)\n");
}

echo "Listening on https://localhost:8443\n";
while (true) {
    // the TLS handshake happens inside stream_socket_accept()
    $conn = @stream_socket_accept($server, -1);
    if ($conn === false) {
        continue; // failed handshake, e.g. client rejected the certificate
    }
    fread($conn, 8192); // read (and ignore) the request
    $body = "Hello over TLS\n";
    fwrite($conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
        . 'Content-Length: ' . strlen($body) . "\r\nConnection: close\r\n\r\n" . $body);
    fclose($conn);
}

Test it with curl --cacert server.crt https://localhost:8443/. In production, TLS is normally terminated by the web server (nginx, Apache, Caddy) or a load balancer, not by PHP.

To upgrade an existing plain connection (STARTTLS, as used by SMTP), call stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) after the protocol has negotiated the switch.

Serving pages over HTTPS

When PHP runs behind a web server, the server handles TLS. Your code still needs to know whether the request was secure, for redirects, absolute URLs and cookies:

<?php
function isHttps(): bool
{
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
        return true;
    }
    // Only trust this header if requests come exclusively through your own proxy
    $trustedProxies = ['10.0.0.5'];
    return in_array($_SERVER['REMOTE_ADDR'] ?? '', $trustedProxies, true)
        && ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
}

if (!isHttps()) {
    $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('Location: ' . $url, true, 301);
    exit;
}

// Tell browsers to use HTTPS for this site for the next year
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');

In real applications validate HTTP_HOST against a list of known host names before using it in a redirect, or do the redirect in the web server configuration.

Cookies that carry session ids or tokens must have the Secure flag, so the browser never sends them over plain HTTP:

<?php
setcookie('token', $token, [
    'expires'  => time() + 3600,
    'path'     => '/',
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

// For sessions, set before session_start() (or in php.ini)
ini_set('session.cookie_secure', '1');
ini_set('session.cookie_httponly', '1');
session_start();

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents