标签 DDNS 下的文章

https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record
先记下来
前期工作:
申请token,到这里:
https://dash.cloudflare.com/profile/api-tokens
创建对应域名的token。
权限需要两行,zone-edit,dns-edit。
cloudflare_dns_api.png

用PHP来实现的。因为windows下面不能用shell。

<?php
include "cloudflareAPI.php";

$ip_v4=file_get_contents("https://api-ipv4.ip.sb/ip");
$ip_v6=file_get_contents("https://api-ipv6.ip.sb/ip");
$cf=new CFAPI;
$cf->apikey="XXXXXXXXXXXXXXXXXXXXXXX"; //token
$cf->email="admin@kele.im";
$cf->zoneid="xxxxxxxxxxxxxxxx"; //域名的zoneid在域名overview页面右下角
echo $cf->updateDNS("ddns.domain.com",$ip_v4);
?>
<?php

class CFAPI {

    public $apikey;
    public $email;
    public $zoneid;

    private function curl($url,$method="GET",$data=null)
    {
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);                                                                     
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer '.$this->apikey.'',
        'Content-Type:application/json'
        ));
        if (!empty($data)) {
            $data_string = json_encode($data);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
        }
        $sonuc = curl_exec($ch);
        curl_close($ch);
        return $sonuc;
    }

    private function getDomainID($domain)
    {
        //$result=$this->curl("https://api.cloudflare.com/client/v4/zones/".$this->zoneid."/dns_records?name=".$domain);
        $result=$this->curl("https://api.cloudflare.com/client/v4/zones/".$this->zoneid."/dns_records?name=".$domain."&type=A");
        var_dump($result);
        $json=json_decode($result);
        if (!empty($json->result) and $json->success) {
            return $json->result[0]->id;
        }
        else
        {
            return "";
        }

    }

    public function getuser()
    {
        return $this->curl("https://api.cloudflare.com/client/v4/user");
    }

    public function updateDNS($domain,$ip,$type="A",$ttl=120)
    {
        $domainid=$this->getDomainID($domain);
        $data = array(
            'type' => ''.$type.'',
            'name' => ''.$domain.'',
            'content' => ''.$ip.'',
            'proxied' => false,
            'ttl' => $ttl
        );
        if (empty($domainid)) {
            return $this->curl("https://api.cloudflare.com/client/v4/zones/".$this->zoneid."/dns_records","POST",$data);
        }
        else
        {
            return $this->curl("https://api.cloudflare.com/client/v4/zones/".$this->zoneid."/dns_records/".$domainid,"PUT",$data);
        }
        
    }

}

?>