自己的域名比较多,各种应用的子域名一堆,然而需要ssl证书的也多,经常忘记续签而导致网站访问异常的问题,于是想做一个监控ssl证书的功能,因为喜欢php,所以就用php实现这个功能了,核心代码:
/** * 获取证书信息 * @param $url string 域名或者url,(如abc.com或者http://abc.com) * @return array */ function get_cert_info($url) { if (!extension_loaded('openssl') || !is_callable('openssl_x509_parse')){ return ['code' => -1, 'msg' => '请开启openssl扩展']; } //不规范入参处理 $parse = parse_url($url); if (!empty($parse['host'])) { $domain = $parse['host']; } elseif (empty($parse['path'])) { return ['code' => -1, 'msg' => $url . '请输入合法的域名']; } else { //abc.top/x/xx $arr = explode('/', $parse['path']); $domain = $arr[0]; } $context = stream_context_create([ 'ssl' => [ 'capture_peer_cert' => true, 'capture_peer_cert_chain' => true, ], ]); $client = @stream_socket_client("ssl://" . $domain . ":443", $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $context); if ($client == false) { return ['code' => -1, 'msg' => $domain . '未查到可靠信息','err'=>[ 'errno'=>$errno, 'errstr'=>iconv('gbk', 'utf-8', $errstr), ]]; } $params = stream_context_get_params($client); if (empty($params['options']['ssl']['peer_certificate'])) { return ['code' => -1, 'msg' => $domain . '获取信息失败,请确保可以正常访问']; } $cert = $params['options']['ssl']['peer_certificate']; $cert_info = @openssl_x509_parse($cert); return ['code' => 0, 'data' => $cert_info]; } $url = 'blog.alipay168.cn'; $info = get_cert_info($url);
查看结果:
有了时间就可以入库、定时检测了~
参考:https://www.php.net/manual/en/context.ssl.php
基于这个自己用php写了一个开源系统https域名证书监控系统,支持实时通知: https://gitee.com/brisklan/https-manager