php 获取指定 url 的 https 证书信息(证书到期时间)

 
更多

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

打赏

本文固定链接: https://www.cxy163.net/archives/2933 | 绝缘体

该日志由 绝缘体.. 于 2024年08月23日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: php 获取指定 url 的 https 证书信息(证书到期时间) | 绝缘体
关键字: , , , ,

php 获取指定 url 的 https 证书信息(证书到期时间):等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter