使用API在CloudFlare上批量添加域名的DNS - www转@ - by PHP

目标

为CloudFlare上的所有的域名添加一条DNS记录(www.xxx.com转xxx.com):  

TYPE NAME CONTENT
CNAME www @


另一个例子:  https://blog.csdn.net/qq285744011/article/details/88357409 
每个域名,只允许存在一条A纪录(where type = 'A' and name = 'yourdomain.com' and content = '6.6.6.6')
多了就删除,
不存在就创建。

步骤

  1. 获取你的所有域名的zone_identifier, 保存为数组 {'xxx.com':'e611410512d92c5','ilovechina.cn':'130bb1bffe30d2e34'} 参考https://blog.csdn.net/qq285744011/article/details/88345077
  2. 读取以上数组,遍历,使用cURL进行API请求,如果已存在就会报错,忽略并进行下一个,如果不存在就ADD
  3. 遍历完成,即完成,登陆CF检查DNS设置。

关键代码

    $curl_url = "https://api.cloudflare.com/client/v4/zones/{$zoneID}/dns_records";
    $curl_head = array(
        "X-Auth-Email: {$x_email}",
        "X-Auth-Key: {$x_auth_key}",
        "Content-Type: application/json"
    );
    $data = array(
        'type' => 'CNAME',
        'name' => 'www.'.$domain,
        'content' => $domain,
        'proxied' => true,
        'ttl' => 1
    );

 

完整代码

<?php
    /**
     * Title:  使用API在CloudFlare上批量添加域名的DNS - www转@ - by PHP
     * Author: Rudon <[email protected]>
     * Date:   2020-01-28
     * 
     * 
     * === 第一步 ===
     * 获取你的所有域名的zone_identifier, 保存为./result_zone_id_and_domain.json
     * 可以参考:
     * 获取CloudFlare上的所有域名的ID (zone_identifier) - by PHP 
     * https://blog.csdn.net/qq285744011/article/details/88345077
     * 
     * === 第二步 ===
     * 遍历json文件里的域名,利用PHP的cURL进行API请求,新建记录,核心参数如下:
        curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records" \
            -H "X-Auth-Email: [email protected]" \
            -H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
            -H "Content-Type: application/json" \
            --data '{"type":"CNAME","name":"www.example.com","content":"example.com","ttl":{},"priority":10,"proxied":false}'
     * 
     * 
     * <本文的目标>
     * 每个域名,添加一条CNAME纪录(where type = 'CNAME' and name = 'www.example.com' and content = 'example.com'
     * 存在就跳过,
     * 不存在就创建。
     * 
     */


    /* 域名多的话,需要设置max_execution_time,防止超时 */
    ini_set('max_execution_time', 1800);


    /* 账号信息 */
    $x_email = '[email protected]';
    /* 登陆后,右上角头像,MyProfile,API Tokens,Global API Key */
    $x_auth_key = '165be6605dd605dd1419c1be6c16540'; 

    /**
     * 数组for 域名:ID
     * https://blog.csdn.net/qq285744011/article/details/88345077
     * 
     * $zones = array(
     *      'xxx.com' => 'e611410512d92c5',
     *      'ilovechina.cn' => '130bb1bffe30d2e34'
     * );
     */
    $path_zones = dirname(__FILE__).'/result_zone_id_and_domain.json';
    if(!is_file($path_zones)){
        die('找不到数组 for 域名:ID');
    }
    $zones = json_decode(file_get_contents($path_zones), true);

    /**
     * 实时结果日志,请tail -f api.log
     */
    $log_file_name = 'api.log';
    $log_file = dirname(__FILE__) . '/' .$log_file_name;
    file_put_contents($log_file, ''); /* Refresh every time */


    /**
     * cURL简化
     * 
     * @param type $url
     * @param type $my_head_array | array() | array('key1:value1', 'key2:value2')
     * @return string 
     * @link https://blog.csdn.net/qq285744011/article/details/87859137
     */
    function geturl($url, $my_head_array = array()) {
        $headerArray = array("Content-Type: application/json;", "Accept: application/json");
        if (is_array($my_head_array) && count($my_head_array)) {
            $headerArray = $my_head_array;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    
    /* cURL简化 */
    function posturl($url, $my_head_array = array(), $data = array()) {
        $headerArray = array("Content-Type: application/json;", "Accept: application/json");
        if (is_array($my_head_array) && count($my_head_array)) {
            $headerArray = $my_head_array;
        }

        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    function logdown ($message = '') {
        global $log_file;
        if(is_file($log_file)){
            file_put_contents($log_file, $message, FILE_APPEND);
        }
    }

    


    /**
     * 开始遍历域名,写入CNAME类型的NS记录
     * https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
     * 
     */
    foreach ($zones as $domain => $zoneID) {
        $curl_url = "https://api.cloudflare.com/client/v4/zones/{$zoneID}/dns_records";
        $curl_head = array(
            "X-Auth-Email: {$x_email}",
            "X-Auth-Key: {$x_auth_key}",
            "Content-Type: application/json"
        );
        $data = array(
            'type' => 'CNAME',
            'name' => 'www.'.$domain,
            'content' => $domain,
            'proxied' => true,
            'ttl' => 1  // 数字1代表自动ttl
        );

        logdown('=========='.date('Y-m-d H:i:s').'==========='.PHP_EOL);
        logdown('Dealing with '.$domain.PHP_EOL);
        //continue;

        $response_json_str = posturl($curl_url, $curl_head, $data);
        $res_arr = json_decode($response_json_str, TRUE);
        if (!is_array($res_arr) || !count($res_arr)) {
            die('Sorry, invalid response:<br />' . $response_json_str);
        }
        if (!key_exists('success', $res_arr)) {
            die('Failed: <br />' . $response_json_str.'<br /><br /><br />'.json_encode($data));
            
        } else {
            if(!$res_arr['success']){
                if($res_arr['errors'][0]['code'] == 81053 || $res_arr['errors'][0]['message'] == 'An A, AAAA or CNAME record already exists with that host.'){
                    logdown('Repeat record ignored for '.$domain.PHP_EOL);
                    
                } else {
                    die('Failed: <br />' . $response_json_str.'<br /><br /><br />'.json_encode($data));
                }
            } else {
                logdown('Created for '.$domain.PHP_EOL);
            }
        }

        if (!key_exists('result', $res_arr)) {
            die('Missing key `result`: <br />' . $response_json_str);
        }



    }

    
    
    $result_link = '<a href="./'.$log_file_name.'">'.$log_file_name.'</a>';
    die('Finished!  Please check the log file: '.$result_link);


发布了166 篇原创文章 · 获赞 58 · 访问量 66万+

猜你喜欢

转载自blog.csdn.net/qq285744011/article/details/104097792