Skip to content

Instantly share code, notes, and snippets.

@ariia-git
Forked from fredsted/ddns-api.php
Created May 31, 2020 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ariia-git/066bb8bdb3a80d24e6d3f38bfa9b3535 to your computer and use it in GitHub Desktop.
Save ariia-git/066bb8bdb3a80d24e6d3f38bfa9b3535 to your computer and use it in GitHub Desktop.
Virtualmin Dynamic DNS (DDNS) server
<?php
// This script receives DDNS updates via HTTP
// example: http://server/ddns-api.php?name=home = updates home.domain.com to IP of requester
define('DDNS_DATA_FILE', '/home/ddns/ddns.json');
define('DDNS_DOMAIN', 'example.com');
header("Content-type: text/plain");
class ddns {
public $name;
public $ip;
}
function print_data($data) {
foreach ($data as $dat) {
echo "{$dat->name}.".DDNS_DOMAIN.":\t\t{$dat->ip}\n";
}
}
$data = json_decode(file_get_contents(DDNS_DATA_FILE)) or new stdObject();
if (!isset($_GET['name'])) {
echo "Not enough parameters. Available params:\n";
echo " &name name of subdomain\n";
echo " &ip the ip - can be left blank\n";
echo " &action the action of the command. default is update, can also be delete.\n";
echo "\n";
print_data($data);
die();
}
if (isset($_GET['ip'])) {
$ip = $_GET['ip'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
if (!isset($_GET['action']) || ($_GET['action'] == 'update')) {
$object = new ddns;
$object->name = $_GET['name'];
$object->ip = $ip;
$data->{$object->name} = $object;
} elseif ($_GET['action'] == 'delete') {
unset($data->{$_GET['name']});
}
file_put_contents(DDNS_DATA_FILE, json_encode($data));
print_data($data);
#!/usr/bin/php
<?php
// This script should run as cronjob under root and parses the DDNS data
define('DDNS_DATA_FILE', '/home/ddns/ddns.json');
define('DDNS_DOMAIN', 'example.com');
$dns_entries = file_get_contents(DDNS_DATA_FILE);
$dns_entries = json_decode($dns_entries);
$domain = DDNS_DOMAIN;
$virtualmin_bin = "/usr/sbin/virtualmin";
$modify_dns_cmd = "modify-dns --domain $domain";
$command_remove = "$virtualmin_bin $modify_dns_cmd --remove-record";
$command_add = "$virtualmin_bin $modify_dns_cmd --add-record-with-ttl";
$output = "\n\n\n---------------------\n";
$output .= date('l jS \of F Y h:i:s A') . "\n\n";
foreach ($dns_entries as $entry) {
// Remove old DNS thing.
$command = "$command_remove \"{$entry->name} A\"";
$output .= "-> " . $command . "\n";
$output .= shell_exec($command) . "\n";
// Add new DNS thing.
$command = "$command_add \"{$entry->name} A 600 {$entry->ip}\"";
$output .= "-> " . $command . "\n";
$output .= shell_exec($command) . "\n";
}
file_put_contents("/var/log/ddns.log", $output, FILE_APPEND);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment