php 获取指定 url 的 https 证书信息(证书到期时间)。
<?php /** * 获取指定 url 的 https 证书信息 * @param string $url * @return array|false * @throws Exception */ function getCertificateInfo($url) { // 创建上下文,设置 SSL/TLS 选项 $context = stream_context_create([ 'ssl' => [ 'capture_peer_cert' => true, ], ]); // 从 URL 连接到 SSL/TLS 端点 $client = stream_socket_client("ssl://$url:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context); if (!$client) { throw new Exception("Unable to connect to $url: $errstr ($errno)"); } // 从流中获取证书 $params = stream_context_get_params($client); $cert = $params['options']['ssl']['peer_certificate']; // 关闭流 fclose($client); // 获取证书信息 $certInfo = openssl_x509_parse($cert); if ($certInfo === false) { throw new Exception("Unable to parse certificate."); } return $certInfo; } try { // 指定 URL $url = 'www.phpernote.com'; // 获取证书信息 $certInfo = getCertificateInfo($url); // 打印证书信息 echo "Subject: " . implode(', ', array_map(function ($key, $value) { return "$key=$value"; }, array_keys($certInfo['subject']), $certInfo['subject'])) . "\n"; echo "Issuer: " . implode(', ', array_map(function ($key, $value) { return "$key=$value"; }, array_keys($certInfo['issuer']), $certInfo['issuer'])) . "\n"; echo "Valid From: " . date('Y-m-d H:i:s', $certInfo['validFrom_time_t']) . "\n"; echo "Valid To: " . date('Y-m-d H:i:s', $certInfo['validTo_time_t']) . "\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage(); }
获取结果类似如下:
Subject: CN=www.phpernote.com Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=Encryption Everywhere DV TLS CA - G2 Valid From: 2024-08-24 08:00:00 Valid To: 2024-11-22 07:59:59