TLS Hostname Verification in PHP - Encryption Is Not Endpoint Identity
An HTTPS request can be encrypted and still reach the wrong endpoint if the client does not verify who is at the other end. That sounds contradictory only because “TLS is enabled” compresses several different checks into one phrase. For a PHP application calling an API, downloading a feed, or sending a webhook, the useful question is not merely whether the connection uses encryption. It is: which server did the client authenticate?
This distinction matters when a certificate error appears and the tempting fix is to disable verification. The request may start working, but the failure has not been resolved; the client has stopped asking an important question. This article separates the checks involved, maps them to PHP cURL and stream options, and keeps the conclusion deliberately narrow. A valid TLS connection authenticates a service identity under a configured trust model. It does not prove that the service is honest, that its application is secure, or that its response is safe to use.
Encryption, certificate trust, and service identity are different checks
Correctly configured TLS can provide confidentiality, integrity, and server authentication, as summarized by the OWASP Transport Layer Security Cheat Sheet. Those properties depend on more than negotiating an encrypted channel. For ordinary certificate-based HTTPS, a client needs at least two related but distinct answers:
- Can this certificate be validated to a trust anchor the client accepts? This is certification-path or peer verification. It checks the chain of signatures, validity conditions, and the client's configured CA trust.
- Does the certificate identify the service the client intended to reach? This is service-identity or hostname verification. It compares an expected identifier with an identifier presented in the server certificate.
A trusted chain without a matching name is not enough. A certificate for files.example.net should not authenticate billing.example.com merely because both chains end at a trusted CA. The reverse is also incomplete: a matching name in a certificate does not help if the client cannot establish that the certificate belongs to a trusted certification path.
The current RFC 9525 calls the identity expected by the client a reference identifier and an identity carried by the certificate a presented identifier. For a conventional request to https://api.example.com/, the URL normally supplies the reference DNS name api.example.com. The client then looks for a permitted matching identifier in the certificate.
The URL name is part of the security decision
For DNS names, RFC 9525 specifies identifiers in the certificate's subjectAltName extension and says not to use the free-form Common Name field to identify a service. Matching is case-insensitive for ordinary ASCII DNS labels. A wildcard, where supported, is constrained to the complete left-most label and matches only one label. Thus *.example.com can match api.example.com, but it does not match v1.api.example.com.
An IP literal is a different identifier type. If code requests https://192.0.2.10/, the reference identity is that IP address. RFC 9525 requires an exact match against an iPAddress entry in subjectAltName. A certificate containing only the DNS name api.example.com does not become a match just because DNS currently maps that name to 192.0.2.10.
This is one reason replacing a hostname with an IP address to “work around DNS” often creates a certificate error. The error can be accurate: the client asked to authenticate an IP address that the certificate never claimed. A sound fix is to restore the intended hostname, or issue a certificate containing the necessary IP identifier when an IP-based identity is genuinely required. Turning off name checks changes the trust decision rather than repairing it.
What the two cURL options actually control
PHP's cURL extension exposes libcurl's two principal verification controls. Their similar names make them easy to treat as one switch, but the libcurl peer-verification documentation and host-verification documentation describe separate jobs:
CURLOPT_SSL_VERIFYPEERchecks whether the peer certificate can be authenticated through the configured CA trust. Its libcurl default is enabled.CURLOPT_SSL_VERIFYHOSTchecks whether the certificate's identity matches the hostname or address in the URL. Its strict libcurl value and default are2.
Modern code should leave both checks enabled. It can make that policy explicit where a shared options array, framework, or future refactor might otherwise obscure it:
<?php
$url = 'https://api.example.com/v1/status';
$handle = curl_init($url);
if ($handle === false) {
throw new RuntimeException('Unable to initialize cURL');
}
$optionsSet = curl_setopt_array($handle, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
if (!$optionsSet) {
throw new RuntimeException('Unable to configure cURL');
}
$body = curl_exec($handle);
if ($body === false) {
throw new RuntimeException('HTTPS request failed: ' . curl_error($handle));
}
$status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
The example is intentionally incomplete as an API client: it does not decide which status codes are acceptable, validate a content type, limit response size, or parse a schema. Those are separate application controls. The TLS settings answer only whether cURL can establish the authenticated connection under its current trust configuration.
Explicit settings are not automatically safer than defaults. A wrapper can overwrite them later, and the actual CA source depends on how curl and its TLS backend were built. The curl certificate-verification guide documents platform-dependent CA-store behavior. Review the final options and deployment environment rather than assuming that seeing two constants in one file proves the runtime policy.
PHP streams have the same two-part model
The PHP stream layer uses different names for the same conceptual split. According to the PHP SSL context documentation, verify_peer and verify_peer_name both default to true. If peer_name is not supplied, PHP infers it from the hostname used to open the stream.
<?php
$context = stream_context_create([
'http' => [
'timeout' => 15,
'ignore_errors' => true,
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
],
]);
$body = file_get_contents(
'https://api.example.com/v1/status',
false,
$context
);
if ($body === false) {
throw new RuntimeException('HTTPS stream request failed');
}
Again, the example shows connection policy, not a complete HTTP abstraction. Error handling for streams can require inspecting warnings or using a library that exposes failures more cleanly. The important review point is that verify_peer_name must not quietly become false when code moves between development and production.
A private CA is a trust configuration problem, not a reason to skip checks
Internal services commonly use certificates that public CA stores do not recognize. That does not make strict verification impossible. It means the client needs an appropriate private trust anchor. curl can receive a CA bundle through CURLOPT_CAINFO (or a suitable CA directory through CURLOPT_CAPATH), while PHP streams offer cafile and capath.
curl_setopt_array($handle, [
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CAINFO => '/etc/ssl/local-ca.pem',
]);
The file in this example is a trust input, so its origin, contents, ownership, permissions, and update process matter. Downloading whatever certificate a server happens to present and immediately trusting it would collapse the distinction between observation and trust. A private CA should be distributed through a controlled channel, and the leaf certificate still needs an identifier matching the service name.
A self-signed leaf can be trusted explicitly in a tightly controlled system, but that is a different trust model with its own provisioning and rotation costs. The label “self-signed” neither makes a certificate magically acceptable nor explains how clients obtained a trustworthy copy. For many internal services, a small private CA is easier to manage than separately pinning every leaf certificate, but the right choice depends on the system.
Redirects and alternate connection addresses need careful wording
If a client follows a redirect from one host to another, the new HTTPS connection must authenticate the new URL's host. The original server's certificate does not vouch for an unrelated redirect target. Redirect policy also has concerns beyond TLS, including whether credentials are forwarded and whether the destination is allowed. Hostname verification is necessary, but it is not an allowlist.
Some clients can connect to one network address while retaining a different URL hostname. This can be useful for testing, service discovery, or routing around DNS, but the security-sensitive reference identity should remain the intended service name. Server Name Indication (SNI) can help a multi-tenant server choose the right certificate; it does not itself verify that certificate. Exact behavior varies by client and TLS backend, so this is a place to use documented connection-override features rather than rewriting the URL casually.
Failure is information, not an obstacle to suppress
RFC 9525 says an automated application should terminate the attempt with a bad-certificate error and log the error when no presented identifier matches its reference identifiers. The wording leaves room for explicit configuration, but verification must not be disabled by default. That is a useful operational principle: treat failure as evidence to diagnose.
A practical investigation can ask:
- What exact hostname or IP address appears in the final URL?
- Which DNS-ID or IP-ID does the leaf certificate present?
- Which CA store is this particular PHP/curl build using?
- Is the server sending the required intermediate certificates?
- Did a proxy, redirect, container image, or environment-specific option change the path?
- Did application code override verification after shared defaults were applied?
Logging should preserve the error category and destination without leaking credentials, request bodies, or sensitive query strings. “Certificate verification failed” is less convenient than a successful request, but it is more honest than silently changing the client from authenticated TLS to encryption without reliable endpoint identity.
What successful verification still does not prove
Successful path and name verification supports a limited statement: the endpoint demonstrated control of a private key corresponding to a certificate valid for the expected service identity under the client's accepted trust anchors and verification rules. It does not prove who wrote the application, whether an account is authorized, whether the server is compromised, or whether returned JSON is semantically true.
That limitation is not a weakness in hostname verification; it is its proper boundary. Application authentication, authorization, response validation, SSRF controls, redirect policy, timeouts, and business rules still have work to do. Security becomes easier to reason about when each control is allowed to make only the claim it can actually support.
Conclusion
“Use HTTPS” is a starting point, not a complete client policy. A PHP client needs a trusted certification path and a matching service identity. cURL expresses those checks through CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST; PHP streams use verify_peer and verify_peer_name. Their secure defaults are worth preserving, and private infrastructure should add the right trust anchor rather than remove the checks.
The next time a certificate error blocks an outbound request, the most useful question may be: which claim failed—the chain of trust, the expected name, or the configuration that connects the two? Answering that question takes longer than setting an option to false, but it repairs the trust model instead of hiding the warning.
References
- RFC 9525: Service Identity in TLS — IETF / RFC Editor, November 2023.
- TLS Certificate Verification — curl project documentation.
- CURLOPT_SSL_VERIFYHOST explained — libcurl documentation.
- CURLOPT_SSL_VERIFYPEER explained — libcurl documentation.
- SSL context options — PHP Manual.
- Transport Layer Security Cheat Sheet — OWASP Cheat Sheet Series.
