WordPress开发中实现SSL证书有效期监测
SSL证书有效期监测,实现相对简单,具体代码如下
<?php
/**
* TIT Theme Customizer
*
* @package TIT
*/
/*
// 每天检查一次 SSL 状态
if ( ! wp_next_scheduled( 'check_ssl_status_daily' ) ) {
wp_schedule_event( time(), 'daily', 'check_ssl_status_daily' );
}
*/
add_action( 'check_ssl_status_daily', 'check_ssl_status_function' );
function check_ssl_status_function() {
$host = parse_url(home_url(), PHP_URL_HOST);
$port = 443;
$contextOptions = [
"ssl" => [
"capture_peer_cert" => true,
"verify_peer" => false,
"verify_peer_name" => false,
],
];
$context = stream_context_create($contextOptions);
$client = @stream_socket_client("ssl://{$host}:{$port}", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
if (!$client) {
send_ssl_notification_email("SSL 检测失败:无法连接到服务器。错误:$errstr");
return;
}
$params = stream_context_get_params($client);
$cert = openssl_x509_parse($params["options"]["ssl"]["peer_certificate"]);
if (!$cert || empty($cert['validTo_time_t'])) {
send_ssl_notification_email("SSL 检测失败:无法解析证书。");
return;
}
$expiryTimestamp = $cert['validTo_time_t'];
$expiryDate = date('Y-m-d', $expiryTimestamp);
$remainingDays = ceil(($expiryTimestamp - time()) / 86400);
$message = "🔐 当前 SSL 证书有效期至:". $expiryDate ."(剩余 $remainingDays 天)";
// 可自定义天数阈值
if ($remainingDays <= 7) {
send_ssl_notification_email("警告:网站 SSL 证书将于 $expiryDate 到期,仅剩 $remainingDays 天,请尽快续期。");
}
send_ssl_notification_email($message);
}
function send_ssl_notification_email($message) {
$admin_email = get_option('admin_email');
$extra_email = 'info@titstudio.com';
$recipients = [$admin_email, $extra_email];
$subject = '【SSL 警告】网站证书问题提醒';
$body = "您好,\n\n您的网站(" . home_url() . ")的 SSL 证书状态如下:\n\n$message\n\n请及时处理以免影响访问。\n\n-- TIT网站监控";
wp_mail($recipients, $subject, $body);
}
// 手动触发测试 SSL 邮件:访问 https://yourdomain.com/?ssl_check_test=1
add_action('init', function () {
if (isset($_GET['ssl_check_test']) && $_GET['ssl_check_test'] == '1') {
check_ssl_status_function();
wp_die('SSL 检查已触发,请检查邮箱'); // 输出提示防止空白页
}
});