php实现ddns
PHP实现DDNS(动态域名解析)的方法
DDNS(Dynamic Domain Name System)用于将动态IP地址映射到固定域名。以下是使用PHP实现DDNS的几种方法:
使用API更新DNS记录
通过调用DNS服务商提供的API(如Cloudflare、阿里云DNS等)实现IP更新。以Cloudflare为例:
<?php
$email = 'your@email.com';
$apiKey = 'your_api_key';
$zoneId = 'your_zone_id';
$recordId = 'your_record_id';
$domain = 'yourdomain.com';
$currentIp = $_SERVER['REMOTE_ADDR']; // 或通过其他方式获取IP
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records/$recordId");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Auth-Email: ' . $email,
'X-Auth-Key: ' . $apiKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'type' => 'A',
'name' => $domain,
'content' => $currentIp,
'ttl' => 120
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
通过cron定时任务
在服务器上设置cron定时执行PHP脚本,定期检查并更新IP:
*/5 * * * * /usr/bin/php /path/to/ddns_script.php
使用文件存储上次IP
避免频繁更新,可记录上次IP进行比对:
$ipFile = '/path/to/last_ip.txt';
$currentIp = file_get_contents('https://api.ipify.org');
if (!file_exists($ipFile) || $currentIp != file_get_contents($ipFile)) {
// 调用API更新DNS
file_put_contents($ipFile, $currentIp);
}
安全增强措施
建议增加身份验证,避免脚本被滥用:
$secretToken = 'your_secret_token';
if ($_GET['token'] !== $secretToken) {
die('Unauthorized');
}
完整示例流程
- 获取当前公网IP(通过外部服务或服务器变量)
- 与上次记录的IP比对
- 若IP变化则调用DNS服务商API更新
- 记录新IP到本地文件
- 设置定时任务自动运行
注意事项:
- 确保API密钥等敏感信息的安全
- 考虑添加失败重试机制
- 不同DNS服务商的API可能有差异
- 生产环境建议添加日志记录功能







