php实现域名授权
域名授权的基本原理
域名授权通常指验证当前访问的域名是否在授权列表中,防止未授权域名使用代码或服务。核心逻辑是通过获取当前访问的域名并与预定义的授权域名列表比对。
获取当前访问域名
通过 $_SERVER['HTTP_HOST'] 或 $_SERVER['SERVER_NAME'] 获取当前域名。需注意过滤端口号和非法字符:
$current_domain = strtolower(trim($_SERVER['HTTP_HOST']));
$current_domain = preg_replace('/:\d+$/', '', $current_domain); // 移除端口
定义授权域名列表
在配置文件中定义允许访问的域名数组:

$allowed_domains = [
'example.com',
'sub.example.com',
'authorized-site.net'
];
验证域名授权
使用 in_array() 进行严格比对,建议开启严格模式检查数据类型:
if (!in_array($current_domain, $allowed_domains, true)) {
header('HTTP/1.1 403 Forbidden');
exit('Domain authorization failed');
}
高级验证方案
对于需要动态更新授权列表的场景,可采用数据库存储授权域名:

// 数据库查询示例(使用PDO)
$stmt = $pdo->prepare("SELECT domain FROM authorized_domains");
$stmt->execute();
$allowed_domains = $stmt->fetchAll(PDO::FETCH_COLUMN);
IP与域名双重验证
结合IP白名单增强安全性:
$allowed_ips = ['192.168.1.100', '203.0.113.45'];
$client_ip = $_SERVER['REMOTE_ADDR'];
if (!in_array($client_ip, $allowed_ips, true) || !in_array($current_domain, $allowed_domains, true)) {
die('Access denied');
}
加密授权机制
对于商业软件分发,可采用加密license文件验证:
- 生成包含域名信息的加密文件
- 程序启动时读取并解密验证
- 使用OpenSSL进行非对称加密:
// 生成license示例
$license_data = ['domain' => 'client-domain.com', 'expiry' => '2025-12-31'];
file_put_contents('license.key', openssl_encrypt(json_encode($license_data), 'AES-256-CBC', $secret_key));
定时验证方案
通过cronjob定期检查域名授权状态:
// 每日执行的验证脚本
if (!verify_domain_authorization()) {
disable_system_functionality();
send_alert_email();
}
注意事项
- 避免在客户端JavaScript中进行验证
- 定期备份授权域名列表
- 对验证失败记录详细日志
- 考虑使用HTTPS防止域名劫持
- 重要系统建议结合硬件加密狗等物理授权方式






