Skip to content

Instantly share code, notes, and snippets.

@joshuapack
Created May 17, 2020 18:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuapack/d07e4d7f0a51e34c5fb7b5670328f144 to your computer and use it in GitHub Desktop.
Save joshuapack/d07e4d7f0a51e34c5fb7b5670328f144 to your computer and use it in GitHub Desktop.
<?php
$zone_identifier = '';
$auth_key = '';
$domain = '';
$public_ip = file_get_contents('https://ipinfo.io');
$public_ip = json_decode($public_ip);
if (!isset($public_ip->ip)) {
echo "unable to get public IP";
die();
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/".$zone_identifier."/dns_records?type=A&name=".$domain);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$auth_key,
'Content-Type: application/json'
));
$output = curl_exec($ch);
$identifier = json_decode($output)->result[0]->id;
curl_close($ch);
$data = '{"type":"A","name":"'.$domain.'","content":"'.$public_ip->ip.'","ttl":1,"proxied":false}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/".$zone_identifier."/dns_records/".$identifier);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$auth_key,
'Content-Type: application/json'
));
$output = curl_exec($ch);
curl_close($ch);
@joshuapack
Copy link
Author

joshuapack commented May 17, 2020

Some notes:

  • Requires CURL PHP extension to be installed an enabled.
  • You can remove the first cloudflare call if you know the ID to that specific zone. less calls are better.
  • Currently uses https://ipinfo.io to work.
  • Make sure to run in cron or schedule it to run. (currently I run every 5 minutes)

You can add your own error logs (make sure to assign $error_log to a writable location):
if no IP present (add before die(); within the IP check conditional statement)

error_log("unable to get public IP: ".print_r($public_ip ,true)."\n", 3, $error_log);

if update fails (add to end of script)

$output = json_decode($output);
if (!isset($output->success) || !$output->success) {
    error_log("cloudflare DNS Update: ".print_r($output ,true)."\n", 3, $error_log);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment