php 通过扫描证书获取到期时间
程序员文章站
2022-07-12 12:30:52
...
记录:通过扫码证书获取到期时间,需要安装OpenSSL拓展
//查询入口
public function getsslOp(){
// 参数存到变量
$scanpath = ROOT_PATH ."/public/ssl/";
$scanexts = "crt";
// 扫描 SSL 证书
$exps = $this->scan_ssl_files($scanpath, $scanexts);
if(count($exps) === 0) {
echo "<pre>";
return "未扫描到 SSL 证书,请检查目录是否存在,以及目录下是否有证书文件\n";
}
// 获取最长的域名
$max_length = 0;
foreach($exps as $key => $value) {
if(mb_strwidth($key) > $max_length) {
$max_length = mb_strwidth($key);
}
}
// 遍历数组
foreach($exps as $key => $value) {
//判断证书状态
$expired = "正常";
$section_time = $value['end_time'] - time();
$padding = str_repeat(" ", $max_length - mb_strwidth($key));
if($section_time <= 2592000 && $section_time > 0){
$expired = "一个月内将会过期";
} elseif(count($value) == 0) {
$expired = "无效";
} elseif($section_time < 0) {
$expired = "已经过期";
}
$end_time = $value['end_time'] !== 0 ? date("Y-m-d H:i:s", $value['end_time']) : 0;
$begin_time = $value['begin_time'] !== 0 ? date("Y-m-d H:i:s", $value['begin_time']) : 0;
$data[$key] = [
'dn' => $value['dn'],
'begin_time' => $begin_time,
'end_time' => $end_time,
'status' => $expired
];
}
echo '<pre>';print_r($data);
}
//获取ssl证书内容
public function get_ssl_expire_time($file) {
$cert = openssl_x509_parse(file_get_contents($file));
$ssl_time['dn'] = $cert['subject']['CN']; //证书保护域名
$ssl_time['begin_time'] = $cert['validFrom_time_t']; //证书开始时间
$ssl_time['end_time'] = $cert['validTo_time_t']; //证书结束时间
return $ssl_time ?? 0;
}
// 扫描目录下的所有 SSL 证书
public function scan_ssl_files($dir, $extensionName = "crt") {
if(!file_exists($dir)) return Array();
if(is_file($dir)) return Array(basename($dir) => $this->get_ssl_expire_time($dir));
$abspath = realpath($dir);
$expiretime = Array();
if($abspath) {
$list = scandir($dir);
foreach($list as $file) {
if($file !== "." && $file !== "..") {
$ext = pathinfo("{$dir}{$file}");
if($ext['extension'] == $extensionName) {
$expiretime["{$file}"] = $this->get_ssl_expire_time("{$dir}{$file}");
}
}
}
}
return $expiretime;
}
结果示例:
上一篇: C# https客户端获取证书的工具方法
下一篇: 联结词的逻辑运算