PHP code for a script that finds the IP address by checking a remote server. If the returned IP is not what is currently in the MyDNS database for the domains A records it is changed accordingly and emails notification of said change. Actions are logged to a text file. If no IP is returned it is logged as null but no changes take place. This prevents setting an empty local IP address when the remote server is not answering.
<?php
// Configuration
$domain='example.com'; // Local domain to update
$db_server = 'localhost';
$db_user = 'db_user';
$db_password = 'db_password';
$log_file = '/var/log/dynamic_ip.log';
$echo_page = 'http://remote_host.com/ip.shtml'; // Where ip.shtml contains only <!--#echo var="REMOTE_ADDR" -->
// Some Initialization
$domain .= '.';
$dns_record = 'A';
$log_message = date('l jS F Y h:i:s A'). ' --- ';
// Find current dynamic IP address
$echoed_ip = trim(file_get_contents($echo_page));
if ($echoed_ip != '') {
// Open ISPConfi3 Database used by MyDNS
$con = mysql_connect($db_server,$db_user,$db_password);
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db('dbispconfig', $con);
// Find the Zone Number for the Domain
$dns_zone = mysql_query("SELECT id FROM dns_soa WHERE origin = $domain");
// Find the Current IP Address
$table_data = mysql_query("SELECT * FROM dns_rr");
$change_flag = false;
while ($item_data = mysql_fetch_array($table_data)) {
if ($item_data['type'] == $dns_record && $item_data['zone'] == $dns_zone) {
$stored_ip = trim($item_data['data']);
if (!($stored_ip == $echoed_ip)) $change_flag = true;
}
}
if ($change_flag) {
$ipmessage=' - IP Changed from '.$stored_ip.' to '.$echoed_ip.' at domain '.$domain;
$log_message .= $ipmessage;
mysql_query("UPDATE dns_rr SET data='$echoed_ip' WHERE type='A' && zone = '$dns_zone'");
mail('someonewhocares@somewhere.net','IP Change',$ipmessage);
} else {
$log_message .= ' No Change. IP remains (',$echoed_ip,')';
}
mysql_close($con);
} else {
$log_message .= ' Null IP Returned. IP remains (',$echoed_ip,')';
}
// Write to Log File
$logging = fopen($log_file, 'a');
fwrite($logging, $log_message);
fclose($logging);
\?\>