php获取ssl证书有效期代码
公司有很多证书,都是用的免费的,所以只有3个月有效期了,所以需要时常关注了。于是百度了下面的代码。
php获取证书有效期的代码,百度的,直接复制过来。
function getCertificateInfo($domainName) {
$context = stream_context_create(['ssl' => [
'capture_peer_cert' => true,
'verify_peer' => false,
'peer_name' => $domainName
]]);
$socket = stream_socket_client("ssl://{$domainName}:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
if (!$socket) {
echo "Unable to connect: $errstr ($errno)<br />\n";
return;
}
$cert = stream_context_get_params($socket);
$certInfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
// 证书有效起止日期
$startDate = date('Y-m-d', $certInfo['validFrom_time_t']);
$endDate = date('Y-m-d', $certInfo['validTo_time_t']);
// 当前日期
$currentDate = new DateTime();
// 证书剩余有效天数
$remainingDays = $currentDate->diff(new Datetime($endDate))->days;
return [
'startDate' => $startDate,
'endDate' => $endDate,
'remainingDays' => $remainingDays
];
}
// 使用示例
$domainName = '66gouzhen.cn'; // 替换为你想检查的域名
$certInfo = getCertificateInfo($domainName);
if ($certInfo) {
echo "证书有效期自:{$certInfo['startDate']} 至:{$certInfo['endDate']}<br />";
echo "证书剩余有效天数:{$certInfo['remainingDays']}天";
} else {
echo "无法获取证书信息";
}