php:获取https证书的信息(PHP 8.1.1)

一,代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
//得到证书的信息
function getCertInfo($url){
    if (!extension_loaded('openssl') || !is_callable('openssl_x509_parse')){
        return ['code' => -1, 'msg' => '请开启php的openssl扩展'];
    }
    //解析url,判断是否存在不合法参数
    $parse = parse_url($url);
    if (!empty($parse['host'])) {
        $domain = $parse['host'];
    } elseif (empty($parse['path'])) {
        return ['code' => -1, 'msg' => $url . '请输入合法的域名'];
    } else {
        $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),
                ]];
    }
    //得到context的参数
    $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];
}
//要查询的域名
$host = 'www.baidu.com';
$info = getCertInfo($host);
 
if ($info['code'] != 0){
    echo "访问出错:".$info['msg']."\n";
    exit;
}
//得到证书的时间,并打印
$data = $info['data'];
$dn = $data['subject']['CN']; //证书保护域名
$validFrom_time_t = date('Y-m-d H:i:s', $data['validFrom_time_t']); //证书开始时间
$validTo_time_d = date('Y-m-d H:i:s', $data['validTo_time_t']); //证书结束时间
 
echo "证书保护域名:" . $dn . ":\n";
echo "证书开始时间:" . $validFrom_time_t . ":\n";
echo "证书结束时间:" . $validTo_time_d . ":\n";
 
?>

说明:我们主要是为了获取证书的结束时间,可以用来发送提醒信息,避免证书过期

二,测试效果

root@lhdpc:/data/work/cert# /usr/local/soft/php8/bin/php ./certinfo.php 
证书保护域名:baidu.com:
证书开始时间:2023-07-06 01:51:06:
证书结束时间:2024-08-06 01:51:05:

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/07/27/php-huo-qu-https-zheng-shu-de-xin-xi-php-8-1-1/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

三,查看php的版本:

root@lhdpc:/data/work/cert# /usr/local/soft/php8/bin/php --version
PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies
posted @ 2023-07-27 14:46  刘宏缔的架构森林  阅读(213)  评论(0编辑  收藏  举报