<?php
$api_key = '[APIキー]';
$server_id = 'xsvx1023505';
$servername = $server_id.'.xsrv.jp';
$api_base_url = 'https://api.xserver.ne.jp';
$api_base_path = '/v1/server/'.$servername;
$target = 'silverfox';
$domain = 'noizumi.org';
$url_ip_prog = 'https://yuji.noizumi.org/ip.php';
$url_ip_txt = 'https://yuji.noizumi.org/ip.txt';
$dns_id = '76684883'; // 作成済のDNSレコードID silverfox.noizumi.org
// nslookup から、現在DNSに登録されているIPアドレスを抜き出す。
ob_start();
passthru('nslookup '.$target.'.'.$domain.' ns5.xserver.jp');
$buf = ob_get_clean();
$hosts = '';
if(preg_match_all('/Address:\s+((\d+\.){3}\d+)/',$buf ,$matches)){
$hosts = $matches[1][1];
}
// IPv4を明示的に指定して接続するコンテキストを作成
$context = stream_context_create([
'socket' => [
// IPv4アドレスでバインドする(通常は0.0.0.0:0)
'bindto' => '0.0.0.0:0',
],
]);
$response = file_get_contents($url_ip_prog, false, $context);
if(preg_match('/Your IP address is ([0-9.]*)/', $response, $matches)){
$myip = $matches[1];
}else{
$myip = file_get_contents($url_ip_txt);
}
if($myip==$hosts){
exit(0);
}
$params = array(
'domain' => $domain,
'host' => $target,
'type' => 'A',
'content' => $myip
);
$fields = json_encode($params);
$header = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
'Authorization: Bearer '.$api_key
);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); // IPv4 Only.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // HTTPレスポンス 30x を追跡する。
curl_setopt($ch, CURLOPT_HEADER, false);
$command = '/dns/'.$dns_id;
curl_setopt($ch, CURLOPT_URL, $api_base_url.$api_base_path.$command);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
?>