define('AccessKeyId', 'KEY');
define('AccessKeySecret', 'Secret');
date_default_timezone_set('UTC');
/**
* 获取本机 IP 地址
*/
function getIP() {
$url = 'http://ip.taobao.com/service/getIpInfo.php?ip=myip';
try {
$json = json_decode(file_get_contents($url));
} catch (Exception $e) {
$json = [];
}
if (isset($json->code) && $json->code == 0) {
return $json->data->ip;
}
return '';
}
/**
* 获取请求签名
*/
function getSign($add){
$nonce = time() . rand(11111, 99999);
$time = date('Y-m-d') . 'T' . date('H:i:s') . 'Z';
$data = array(
'AccessKeyId' => AccessKeyId,
'Format' => 'json',
'SignatureMethod' => 'HMAC-SHA1',
'SignatureNonce' => $nonce,
'SignatureVersion' => '1.0',
'Timestamp' => $time,
'Version' => '2015-01-09'
);
$data = array_merge($data, $add);
ksort($data);
$format = http_build_query($data);
$signUrl = 'GET&%2F&' . urlencode($format);
$sign = urlencode(base64_encode(hash_hmac('sha1', $signUrl, AccessKeySecret . '&', true)));
return array('url' => $format, 'sign' => $sign);
}
/**
* 获取域名解析记录
*/
function getDNS($domain) {
$sign = getSign(['Action' => 'DescribeSubDomainRecords', 'SubDomain' => $domain]);
$url = 'https://alidns.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
$dns = json_decode(httpRequest($url));
if (isset($dns->DomainRecords->Record[0])) {
return $dns->DomainRecords->Record[0];
}
return '';
}
/**
* 更新域名解析
*/
function updateDNS($id, $name, $ip) {
$data = array(
'Action' => 'UpdateDomainRecord',
'RecordId' => $id,
'RR' => $name,
'Type' => 'A',
'Value' => $ip,
);
$sign = getSign($data);
$url = 'https://alidns.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
return httpRequest($url);
}
/**
* 发起 HTTP 请求
*/
function httpRequest($url) {
$header = array(
'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding: gzip, deflate',
'Connection: keep-alive',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
if ($error) {
return $error;
} else {
return $data;
}
}
function main() {
$dns = getDNS('www.test.com');
$ip = getIP();
if (isset($dns->RecordId)) {
echo updateDNS($dns->RecordId, 'www', $ip);
}
}
main();