php实现ddns
PHP实现DDNS(动态域名解析)的方法
动态域名解析(DDNS)允许将动态分配的IP地址映射到一个固定的域名上。PHP可以通过调用DNS服务商的API实现这一功能。
获取当前公网IP
使用PHP获取当前服务器的公网IP地址:
$public_ip = file_get_contents('https://api.ipify.org');
if (!$public_ip) {
$public_ip = file_get_contents('http://ipinfo.io/ip');
}
使用Cloudflare API更新DNS记录
Cloudflare提供了完善的API接口用于管理DNS记录。需要准备Zone ID、API Key和DNS记录ID。
$api_key = 'your_cloudflare_api_key';
$email = 'your_cloudflare_email';
$zone_id = 'your_zone_id';
$dns_record_id = 'your_dns_record_id';
$domain = 'yourdomain.com';
$url = "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records/$dns_record_id";
$data = [
'type' => 'A',
'name' => $domain,
'content' => $public_ip,
'ttl' => 120,
'proxied' => false
];
$options = [
'http' => [
'header' => [
"Authorization: Bearer $api_key",
"Content-Type: application/json"
],
'method' => 'PUT',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
使用阿里云DNS API
阿里云也提供DNS管理API,需要AccessKey ID和AccessKey Secret。
$accessKeyId = 'your_access_key_id';
$accessKeySecret = 'your_access_key_secret';
$domain = 'yourdomain.com';
$params = [
'Action' => 'UpdateDomainRecord',
'RecordId' => 'your_record_id',
'RR' => '@',
'Type' => 'A',
'Value' => $public_ip
];
ksort($params);
$queryString = '';
foreach ($params as $key => $value) {
$queryString .= '&' . rawurlencode($key) . '=' . rawurlencode($value);
}
$queryString = substr($queryString, 1);
$signature = base64_encode(
hash_hmac('sha1', 'GET&%2F&' . rawurlencode($queryString), $accessKeySecret . '&', true)
);
$url = "http://alidns.aliyuncs.com/?Signature=" . rawurlencode($signature) . "&" . $queryString;
$result = file_get_contents($url);
定时执行脚本
将上述代码保存为PHP文件,并通过crontab设置定时任务:
*/5 * * * * /usr/bin/php /path/to/ddns.php >/dev/null 2>&1
注意事项
- 确保API密钥和敏感信息的安全,不要直接暴露在代码中
- 各DNS服务商的API可能有调用频率限制
- 脚本需要有网络访问权限
- 建议添加日志功能记录IP变更情况







