php检测SSL证书是否过期

2025-06-05 17:24:29 阅读:4 编辑
function getSSLCertExpiryDate($domain) {
    $context = stream_context_create([
        'ssl' => [
            'capture_peer_cert' => true,
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ]);

    $client = stream_socket_client(
        "ssl://{$domain}:443",
        $errno,
        $errstr,
        30,
        STREAM_CLIENT_CONNECT,
        $context
    );

    if (!$client) {
        throw new Exception("连接失败: {$errno} - {$errstr}");
    }

    $cert = stream_context_get_params($client)['options']['ssl']['peer_certificate'];
    $certInfo = openssl_x509_parse($cert);
    //print_r($certInfo);
    $startDate = date('Y-m-d H:i:s', $certInfo['validFrom_time_t']);
    $expiryDate = date('Y-m-d H:i:s', $certInfo['validTo_time_t']);
    return [$startDate,$expiryDate];
}
Artisan::command('check_domain', function () {
    // 使用示例
    try {
        $domain = 'cim.n7y.cn';
        list($startDate,$expiryDate) = getSSLCertExpiryDate($domain);
        echo "{$domain} 的 SSL 证书{$startDate}开始,将在 {$expiryDate} 过期";
    } catch (Exception $e) {
        echo "错误: " . $e->getMessage();
    }

});