阿里云修改域名对应的ip地址php实现

<?php
date_default_timezone_set("GMT");
class Ali
{
private $accessKeyId = "";//自己的ID
private $accessSecrec = "";//自己的secrec
private static $obj = null;
public static function Obj ()
{
if(is_null(self::$obj))
{
self::$obj = new self();
}
return self::$obj;
}
/**
*获取域名信息列表
*/
public function DescribeDomainRecords()
{
$requestParams = array(
"Action" => "DescribeDomainRecords",
"DomainName" => "eu80.com"
);
$val = $this->requestAli($requestParams);
$val = json_decode($val,true);
return $val;
}

/**
* 更新 ip
* @param $string
*/
public function UpdateDomainRecord($second)
{
$ip = $this->getIp();
//判断当前IP是否与配置IP一致,若不一致则进行修改
$dnsList = $this->DescribeDomainRecords();
//获取当前二级域名的记录
foreach ($dnsList["DomainRecords"]['Record'] as $key => $value) {
if($value["RR"]==$second);
$dns = $value;
}
if($ip != $dns["Value"]){
$requestParams = array(
"Action" => "UpdateDomainRecord",
"RecordId" => $dns["RecordId"],
"RR" => $dns["RR"],
"Type" => $dns['Type'],
"Value" => $ip,
);
$val = $this->requestAli($requestParams);
$this->outPut($val." ".$ip);
}else{
echo "当前IP不需要修改";
}
}
private function requestAli($requestParams)
{
$publicParams = array(
"Format" => "JSON",
"Version" => "2015-01-09",
"AccessKeyId" => $this->accessKeyId,
"Timestamp" => date("Y-m-d\TH:i:s\Z"),
"SignatureMethod" => "HMAC-SHA1",
"SignatureVersion" => "1.0",
"SignatureNonce" => substr(md5(rand(1,99999999)),rand(1,9),14),
);

$params = array_merge($publicParams, $requestParams);
$params['Signature'] = $this->sign($params, $this->accessSecrec);
$uri = http_build_query($params);
$url = 'http://alidns.aliyuncs.com/?'.$uri;
return $this->curl($url);
}


private function getIp()
{
$ip = $this->curl("http://httpbin.org/ip");
$ip = json_decode($ip,true);
return $ip['origin'];
}

private function sign($params, $accessSecrec, $method="GET")
{
ksort($params);
$stringToSign = strtoupper($method).'&'.$this->percentEncode('/').'&';

$tmp = "";
foreach($params as $key=>$val){
$tmp .= '&'.$this->percentEncode($key).'='.$this->percentEncode($val);
}
$tmp = trim($tmp, '&');
$stringToSign = $stringToSign.$this->percentEncode($tmp);

$key = $accessSecrec.'&';
$hmac = hash_hmac("sha1", $stringToSign, $key, true);

return base64_encode($hmac);
}


private function percentEncode($value=null)
{
$en = urlencode($value);
$en = str_replace("+", "%20", $en);
$en = str_replace("*", "%2A", $en);
$en = str_replace("%7E", "~", $en);
return $en;
}

private function curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
$result=curl_exec ($ch);
return $result;
}

private function outPut($msg)
{
echo date("Y-m-d H:i:s")." ".$msg.PHP_EOL;
}
}
//绑定 ip 到域名
Ali::Obj()->UpdateDomainRecord("*");

posted on 2016-06-30 10:37  ~色即是空  阅读(1799)  评论(0编辑  收藏  举报

导航