文档中心
PHP濡備綍鑾峰彇SSL璇佷功鍐呭锛?绉嶆柟娉曡瑙d笌瀹炴垬妗堜緥
时间 : 2025-09-27 16:29:42浏览量 : 2

在网络安全领域,SSL/TLS证书是验证网站身份和加密通信的核心组件。作为PHP开发者,有时需要动态获取SSL证书信息(比如有效期、颁发者等)进行监控或验证。本文将用大白话+实战案例,教你3种PHP获取SSL证书内容的方法。
一、为什么要用PHP获取SSL证书?
想象你管理着100个网站,突然发现某个网站的SSL证书过期了,导致用户访问时出现警告。如果手动检查每个证书,会累到怀疑人生。这时用PHP自动获取并检查证书信息,就能:
- 批量监控:定时检查所有域名证书有效期
- 安全审计:验证证书是否由可信机构颁发
- 故障预警:提前7天邮件提醒证书即将过期
二、方法1:stream_socket_client + openssl_x509_parse(基础版)
这是PHP内置的最简单方法,适合快速获取基础信息:
```php
$host = 'www.example.com';
$port = 443;
// 建立加密连接
$context = stream_context_create(["ssl" => ["capture_peer_cert" => true]]);
$client = stream_socket_client("ssl://{$host}:{$port}", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
// 提取证书信息
$cert = stream_context_get_params($client)['options']['ssl']['peer_certificate'];
$certInfo = openssl_x509_parse($cert);
print_r($certInfo);
```
输出示例:
Array (
[name] => CN=example.com, O=Example Inc, C=US
[validFrom_time_t] => 1672531200
[validTo_time_t] => 1704067199
[issuer] => Array (
[C] => US
[O] => Let's Encrypt
)
)
适用场景:快速检查单个域名的有效期/颁发者。
三、方法2:cURL扩展(带异常处理)
如果需要更稳定的方案(比如处理超时或无效域名),cURL更可靠:
function getSSLCertInfo($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 关键:捕获证书信息
curl_setopt($ch, CURLOPT_CERTINFO, true);
if (curl_exec($ch) === false) {
throw new Exception("连接失败: " . curl_error($ch));
}
$certInfo = curl_getinfo($ch)[0]['certinfo'];
curl_close($ch);
return $certInfo ?: null;
}
// 使用示例
try {
print_r(getSSLCertInfo('https://github.com'));
} catch (Exception $e) {
echo "错误: " . $e->getMessage();
优势对比:
- ? 自动处理HTTPS重定向
- ? 支持设置超时时间(CURLOPT_TIMEOUT)
- ? 需要服务器安装cURL扩展
四、方法3:OpenSSL命令行+PHP(高级技巧)
当需要获取完整PEM格式证书时(比如用于备份),可以结合系统命令:
$domain = 'baidu.com';
$command = "openssl s_client -connect {$domain}:443 -servername {$domain}
exec($command, $output);
// 提取关键字段的正则示例
if (preg_match('/Not After : (.+)/', implode("\n", $output), $matches)) {
echo "过期时间: " . $matches[1];
典型输出内容:
Certificate:
Issuer: C=US, O=Google Trust Services LLC...
Validity:
Not Before: Jan 1 00:00:00 2025 GMT
Not After : Dec 31 23:59:59 2025 GMT
Subject Alternative Name:
DNS: baidu.com,
DNS: www.baidu.com...
五、安全注意事项(避坑指南)
1. 超时设置很重要!
```php
// cURL示例
curl_setopt($ch,CURLOPT_TIMEOUT ,5); //5秒超时
// stream_socket_client示例
stream_set_timeout ($client ,3); //3秒超时
```
2. 验证域名匹配性
```php
if ($certInfo['subject']['CN'] !== 'example.com') {
throw new Exception("域名不匹配!可能是中间人攻击");
}
3. 小心内存泄漏
使用`stream_socket_client`后务必`fclose()`关闭连接。
六、实战案例:批量检查证书有效期
```php
$domains = ['google.com', 'github.com', 'expired.badssl.com'];
foreach ($domains as $domain) {
try {
$info = getSSLCertInfo("https://{$domain}");
$expiryDate = date('Y-m-d', strtotime(openssl_x509_parse(file_get_contents('tls.crt'))['validTo_time_t']));
if (time() > strtotime('-7 days', strtotime(expiryDate))) {
mail('admin@test.com', "[警告] {$domain} SSL即将过期", "剩余天数:" . round((strtotime(expiryDate)-time())/86400));
}
} catch (Exception e) {
log_error("检查{$domain}失败:" . e->getMessage());
}
}
通过以上方法,你可以轻松实现企业级SSL监控系统。根据实际需求选择方案——简单检查用方法1,生产环境推荐方法2,需要原始证书数据时用方法3。
TAG:php 获取ssl证书内容,php curl ssl证书,php获取信息,php获取ua