Skip to content

Instantly share code, notes, and snippets.

@DanCech
Last active November 3, 2016 19:05
Show Gist options
  • Save DanCech/11253787 to your computer and use it in GitHub Desktop.
Save DanCech/11253787 to your computer and use it in GitHub Desktop.
NSONE Dynamic DNS update helper
<?php
/*
* NSONE Dynamic DNS update helper
* Dan Cech <dan@aussiedan.com>
*/
// check a password was provided
if (empty($_SERVER['PHP_AUTH_PW'])) {
header('WWW-Authenticate: Basic realm="DDNS"');
header('HTTP/1.0 401 Unauthorized');
echo 'Unauthorized';
exit;
}
// password is nsone API key, username is ignored
$apikey = $_SERVER['PHP_AUTH_PW'];
// check a valid hostname was provided
if (empty($_REQUEST['hostname']) || !preg_match('/^[a-z0-9-]+\.([.a-z0-9-]+)$/i',$_REQUEST['hostname'],$m)) {
echo 'A valid hostname is required';
exit;
}
// record is complete hostname
$record = $m[0];
// zone is everything after the first period
$zone = $m[1];
// if IP was provided, use that
if (!empty($_REQUEST['myip'])) {
$addr = $_REQUEST['myip'];
// otherwise use caller's IP
} else {
$addr = $_SERVER['REMOTE_ADDR'];
}
$type = preg_match('/:/', $addr) ? 'AAAA' : 'A';
// assemble NSONE API url
$url = 'https://api.nsone.net/v1/zones/'. $zone .'/'. $record .'/'. $type;
// JSON request to set IP as static answer
$params = '{
"zone": "'. $zone .'",
"domain": "'. $record .'",
"type": "'. $type .'",
"answers": [{"answer": ["'. $addr .'"]}]
}';
// initialize curl
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$params);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_FAILONERROR,1);
// user-agent & request headers
curl_setopt($curl,CURLOPT_USERAGENT,'aussiedan ddns 0.1');
curl_setopt($curl,CURLOPT_HTTPHEADER,array(
'Content-type: application/json',
'X-NSONE-Key: '. $apikey,
));
// make request to NSONE
$response = curl_exec($curl);
$errstr = curl_error($curl);
curl_close($curl);
// request failed
if ($response === false) {
echo 'cURL Error: '. $errstr;
exit;
}
echo 'OK';
// end of script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment