Skip to content

Instantly share code, notes, and snippets.

@DanH42
Last active February 6, 2017 21:52
Show Gist options
  • Save DanH42/236b4bb2bef002b11f4329ef06f84443 to your computer and use it in GitHub Desktop.
Save DanH42/236b4bb2bef002b11f4329ef06f84443 to your computer and use it in GitHub Desktop.
Dynamic DNS using the CloudFlare API
<?php
$API_KEY = "xxxxxxxxxxxxxxxx";
$EMAIL = "user@example.com";
$BASE_URL = "https://www.cloudflare.com/api_json.html";
$BASE_URL .= "?tkn=" . $API_KEY . "&email=" . $EMAIL;
function get_json(){
$raw = file_get_contents('addr.json');
if($raw === FALSE || strlen($raw) == 0)
$raw = "{}";
return json_decode($raw, TRUE);
}
function get_machines(){
$raw = file_get_contents('machines.json');
if($raw === FALSE || strlen($raw) == 0)
$raw = "{}";
return json_decode($raw, TRUE);
}
if(isset($_GET['set'])){
$name = $_GET['set'];
$machines = get_machines();
if(isset($machines[$name])){
$machine = $machines[$name];
if(strlen($machine['hash']) != 0 && (!isset($_GET['key']) || $machine['hash'] != sha1($_GET['key'])))
exit("Unauthorized!");
$ip = $_SERVER['REMOTE_ADDR'];
$json = get_json();
// Check if the address has changed
if($json[$name] != $ip){
$json[$name] = $ip;
file_put_contents('addr.json', json_encode($json));
foreach($machine['domains'] as $domain){
// Get a list of subdomains
$res = file_get_contents($BASE_URL . "&z=" . $domain['name'] . "&a=rec_load_all");
$res = json_decode($res, true)['response']['recs']['objs'];
$ids = array();
foreach($res as $search_domain)
$ids[$search_domain['display_name']] = $search_domain['rec_id'];
// Update the entry
$url = $BASE_URL . "&z=" . $domain['name'] . "&a=rec_edit&type=A&service_mode=0&ttl=120";
if(isset($ids[$domain['sub']])){
$url .= "&name=" . $domain['sub'] . "&id=" . $ids[$domain['sub']] . "&content=" . $ip;
$res = json_decode(file_get_contents($url), true);
if(isset($res['result']) && $res['result'] == "success")
echo "+";
else
echo "-";
}else
echo "-";
}
echo " ";
$hosts = "";
foreach($json as $name => $ip)
$hosts .= $ip . "\t" . $name . "\n";
file_put_contents("/etc/hosts.d/dynamic", $hosts);
}else
echo "0 ";
}else
exit("No such domain.");
exit($ip);
}
// Look up an entry
if(isset($_GET['get'])){
$search = strtolower($_GET['get']);
$json = get_json();
if(isset($json[$search]))
exit($json[$search]);
else
exit("0.0.0.0");
}
http_response_code(400);
{
"box1": {
"hash": "",
"domains": [
{
"sub": "box1",
"name": "example.com"
}
]
}, "box2": {
"hash": "7bb19c41ef70714b4f72004618a0f3b37c1a6ca6",
"domains": [
{
"sub": "box2",
"name": "example.com"
}, {
"sub": "box2.dyndns",
"name": "example.net"
}
]
}, "box3": {
"hash": "",
"domains": [
{
"sub": "box3",
"name": "example.com"
}, {
"sub": "box3.dyndns",
"name": "example.net"
}
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment