【码】借助阿里云API实现DDNS
in 代码片段 with 0 comment

【码】借助阿里云API实现DDNS

in 代码片段 with 0 comment

代码来源:自己整理编写
说明:核心在于加密算法,具体的参数请参考阿里云文档

<?php
/**
 * 请先安装ali-sdk:composer require alibabacloud/sdk
 * @since   2020-05-20
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */

require __DIR__ . '/vendor/autoload.php';

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

// Download:https://github.com/aliyun/openapi-sdk-php
// Usage:https://github.com/aliyun/openapi-sdk-php/blob/master/README.md

if ($_SERVER['HTTP_X_REAL_IP']) {
    $ip = $_SERVER['HTTP_X_REAL_IP'];
} else {
    if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) {
            unset($arr[$pos]);
        }
        $ip = trim(current($arr));
    } elseif ($_SERVER['HTTP_CLIENT_IP']) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif ($_SERVER['REMOTE_ADDR']) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
}

$oldIp = file_get_contents('./oldIp');
if( $oldIp == $ip ){
    echo "不需要修改IP地址";
    exit;
}

AlibabaCloud::accessKeyClient('<你的ID>', '<你的Key>')
    ->regionId('cn-hangzhou')
    ->asDefaultClient();

try {
    $result = AlibabaCloud::rpc()
        ->product('Alidns')
        ->version('2015-01-09')
        ->action('UpdateDomainRecord')
        ->method('POST')
        ->host('alidns.aliyuncs.com')
        ->options([
            'query' => [
                'RegionId' => "cn-hangzhou",
                'RecordId' => "<你的域名记录ID>",
                'RR'       => "<参照文档>",
                'Type'     => "A",
                'Value'    => $ip,
            ],
        ])->request();
    file_put_contents('./oldIp', $ip);
    echo 'IP修改成功,域名*****指向了新的IP:'.$ip;
} catch (ClientException $e) {
    echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
    echo $e->getErrorMessage() . PHP_EOL;
}
Comments are closed.