php 实现https Ssl证书到期监听 教程

1.为什么需要

服务器和域名太多,宝塔的自动续签又不管用
三四次因为Ssl证书到期网站不能正常访问导致经济损失了

这里安利一个免费的Ssl申请网站:https://freessl.cn/

2.Php

    function index(){
        $domains = [
            'sumubai.cc',
        ];
        foreach($domains as $domain)
        {
            try{

                $cert_info = get_cert_info($domain);
                $dn = $cert_info['subject']['CN']; //证书保护域名
                $validFrom_time_t = date('m-d H:i', $cert_info['validFrom_time_t']); //证书开始时间
                $validTo_time_d = date('m-d H:i', $cert_info['validTo_time_t']); //证书结束时间

                echo "+-证书保护域名:" . $dn . " -+------------------+\n";
                echo "+-证书开始时间:" . $validFrom_time_t . " -+------------------+\n";
                echo "+-证书结束时间:" . $validTo_time_d . " -+------------------+\n";

                echo '';
                // 7天内到期
                if($cert_info['validTo_time_t']-time() < 7*24*60*60)
                {
                   // 这里我接入了钉钉通知
                   // (new \app\api\controller\DingController)->DingdingGo($domain." 证书到期 ".$validTo_time_d, 1, $domain." 证书到期 ".$validTo_time_d);
                    echo "$domain." 证书到期 ".$validTo_time_d, 1, $domain." 证书到期 ".$validTo_time_d\n";
                }
            } catch (Exception $e)
            {

            }
        }

        die;

    }

    function get_cert_info($domain){

        set_time_limit(100);

        $context = stream_context_create(['ssl' => [

        'capture_peer_cert' => true,
        'capture_peer_cert_chain' => true,

        'verify_peer' =>  false, // You could skip all of the trouble by changing this to false, but it's WAY uncool for security reasons.
        'cafile' => '/etc/ssl/certs/cacert.pem',
        //'CN_match' => 'example.com', // Change this to your certificates Common Name (or just comment this line out if not needed)
        'ciphers' => 'HIGH:!SSLv2:!SSLv3',
        'disable_compression' => true,

        ],

        ]);

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

        if($client==false) {

        return false;

        }

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

    index();

3. 自动运行

代码弄好了之后就是自动运行了
宝塔添加计划任务即可

图片alt


苏慕白 发布于  2022-5-25 18:56