|
| 1 | +<?php |
| 2 | + |
| 3 | +require_once __DIR__ . '/../vendor/autoload.php'; |
| 4 | + |
| 5 | +use dnsomatic\Factory; |
| 6 | + |
| 7 | +// DNS-O-Matic Username |
| 8 | +define('DNSOMATIC_USER', ''); |
| 9 | +// DNS-O-Matic Password |
| 10 | +define('DNSOMATIC_PASS', ''); |
| 11 | +// DNS-O-Matic Hostname |
| 12 | +define('DNSOMATIC_HOST', ''); |
| 13 | +// Output messages to stdout |
| 14 | +define('VERBOSE', true); |
| 15 | +// IP Address local cache |
| 16 | +define('IP_CACHE', __DIR__ . '/ip.cache'); |
| 17 | +// Log file |
| 18 | +define('LOG_FILE', __DIR__ . '/dnsomatic.log'); |
| 19 | + |
| 20 | + |
| 21 | +try { |
| 22 | + if (VERBOSE) { |
| 23 | + echo 'Starting..', PHP_EOL; |
| 24 | + } |
| 25 | + |
| 26 | + $checker = Factory::createChecker(); |
| 27 | + // Resolves current IP Address |
| 28 | + $ipAddr = $checker->exec(); |
| 29 | + if (VERBOSE) { |
| 30 | + echo 'Resolved IP Address: ', $ipAddr, PHP_EOL; |
| 31 | + } |
| 32 | + |
| 33 | + // Retrieves last IP Address from local cache |
| 34 | + $cached = ''; |
| 35 | + if (is_file(IP_CACHE)) { |
| 36 | + $cached = trim(file_get_contents(IP_CACHE)); |
| 37 | + if (VERBOSE) { |
| 38 | + echo 'Cached IP Address: ', $cached, PHP_EOL; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // If resolved IP Address and cached IP Address don't match |
| 43 | + if ($ipAddr !== $cached) { |
| 44 | + if (VERBOSE) { |
| 45 | + echo 'Updating DNS-O-Matic..', PHP_EOL; |
| 46 | + } |
| 47 | + |
| 48 | + // Update DNS-O-Matic with current IP Address |
| 49 | + $updater = Factory::createUpdater(DNSOMATIC_USER, DNSOMATIC_PASS); |
| 50 | + $updater |
| 51 | + ->setHostname(DNSOMATIC_HOST) |
| 52 | + ->setMyip($ipAddr); |
| 53 | + $updater->exec(); |
| 54 | + |
| 55 | + // Stores current IP Address in local cache |
| 56 | + file_put_contents(IP_CACHE, $ipAddr, LOCK_EX); |
| 57 | + } |
| 58 | +} catch (\Exception $exception) { |
| 59 | + // Exceptions are sent to the log file |
| 60 | + $logLine = sprintf( |
| 61 | + '[%s] %s (%s:%d)', |
| 62 | + date('d/m/Y H:i:s'), |
| 63 | + $exception->getMessage(), |
| 64 | + $exception->getFile(), |
| 65 | + $exception->getLine() |
| 66 | + ); |
| 67 | + if (VERBOSE) { |
| 68 | + echo $logLine, PHP_EOL; |
| 69 | + } |
| 70 | + |
| 71 | + file_put_contents( |
| 72 | + LOG_FILE, |
| 73 | + $logLine, |
| 74 | + FILE_APPEND | LOCK_EX |
| 75 | + ); |
| 76 | +} finally { |
| 77 | + if (VERBOSE) { |
| 78 | + echo 'Done', PHP_EOL; |
| 79 | + } |
| 80 | +} |
0 commit comments