php 实现ssl
在 PHP 中实现 SSL/TLS 加密
启用 HTTPS 的服务器配置
确保 Web 服务器(如 Apache 或 Nginx)已正确配置 SSL 证书。Apache 的典型配置如下:
<VirtualHost *:443>
ServerName example.com
SSLEngine on
SSLCertificateFile /path/to/cert.pem
SSLCertificateKeyFile /path/to/key.pem
SSLCertificateChainFile /path/to/chain.pem
</VirtualHost>
强制 HTTPS 重定向
在 PHP 脚本或 .htaccess 中强制 HTTP 跳转到 HTTPS:
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
cURL 的 SSL 请求
使用 cURL 进行安全的 HTTPS 请求时需验证证书:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CAINFO, "/path/to/cacert.pem");
$response = curl_exec($ch);
curl_close($ch);
流上下文 SSL 配置
通过流上下文(stream context)进行 SSL 请求:
$context = stream_context_create([
'ssl' => [
'verify_peer' => true,
'cafile' => '/path/to/cacert.pem'
]
]);
$response = file_get_contents('https://example.com', false, $context);
验证 SSL 证书有效性
检查远程服务器的证书有效性:
$socket = stream_socket_client("ssl://example.com:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
$cert = stream_context_get_params($socket)['options']['ssl']['peer_certificate'];
openssl_x509_parse($cert); // 返回证书详细信息
生成自签名证书(开发环境)
OpenSSL 命令生成自签名证书:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
PHP 7.1+ 的 SSL 改进
PHP 7.1 后支持更灵活的 SSL/TLS 选项:
$context = stream_context_create([
'ssl' => [
'ciphers' => 'TLS_AES_256_GCM_SHA384',
'verify_peer_name' => false // 仅限测试环境
]
]);
检查当前协议
判断当前请求是否使用 HTTPS:
$isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| $_SERVER['SERVER_PORT'] == 443;
关键注意事项:
- 生产环境必须使用可信 CA 签发的证书
- 自签名证书仅适用于开发和测试
- 禁用 SSLv2/SSLv3 等不安全协议
- 定期更新服务器 OpenSSL 版本







