IP-changed notifier without crontab
By rockia on Dec 31, 2011 with Comments 0
I wrote about how to notify myself upon IP changes via email for Home Servers quite a while ago. The theory was simple; just one PHP script to detect the current IP address and compare it with the one stored in a text file. If the IP was changed, then update the text file and send myself an email about the change. Thanks to the crontab in Linux, the PHP page will be visited at a certain time interval.
And today, I am introducing another version of this notifier that doesn’t need crontab’s help.
<?php
ignore_user_abort();//Once the page is visited, even the user close the browser, the script will continue running
set_time_limit(0); // "0" means there is NO limit
$interval=60*30; //Check iP every 30 minutes, you can set your own limit here, the unit is in seconds
do{
$content = file('ip.txt');
$run = require_once('switch.php'); //Controller
if(!$run) die('process abort');
$ip=file_get_contents('http://www.rockia.com/ip.php');
if($content[0] != $ip){
$handle = fopen('ip.txt','w');
fwrite($handle,$ip);
fclose($handle);
$to = "[email protected]";
$subject = "Home Server Public IP changed!";
$body = "The new IP addresss is ".$ip;
mail($to, $subject, $body);
sleep($interval);
}
}while(true);
?>
Everything looks pretty much the same, except now we don’t need crontab’s help and the script will be run every half an hour.
Just need to point out one thing. In line 08, I put a controller there. This controller “switch.php” is important because once the script is running, you won’t be able to stop it even if you replace the file because the program was already loaded in the server’s memory. However, if we put a little switch there, everything the program is running, it will first seek for the switch. If it’s on, then the script will keep running, otherwise, it will just stop and do another iteration of the while loop.
In order to explain better, I can show you the sourcecode for the switch.php .
<?php return True; ?>
Easy, huh?
Filed Under: Programming