I was wondering if there's a way to have a php script on my web server email me whenever a file from another web server changes.
For instance, there's this file that changes frequently: http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json
I blog about a game and that file is very important for creating post on updates before my competitors. I often forget to check it though.
Is there a way to have a script email me whenever that file updates, or check that file to see if it has updated, and email me if it has?
You need have this two files in same folder.
In scriptForCron.php write:
$url='http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$execute = curl_exec($ch);
$fp=fopen('old.json','w+');
$oldjson=fread($fp,filesize('old.json'));
if($execute!=$oldjson){
mail('your@mail.com','Yoohoo', 'File changed');
fputs($fp,$execute);
}
fclose($fp);
And then add scriptForCron.php to cron job. You can ask hosting support for it.
Use crontab to setup checking script to run once a minute and compare this file with your locally stored version (or use md5 checksums instead - it will differ if file changes).
file_get_contents('http://url-to-file', 'checkfile.tmp');
if (md5(file_get_contents('lastfile.tmp')) != md5(file_get_contents('checkfile.tmp')))
{
//copy checkfile to lastfile
unlink('lastfile.tmp');
copy('checkfile.tmp', 'lastfile.tmp');
//send email or do something you want ;)
}
This code does not check for updates in realtime - it would be pretty much impossible - but every 1 hour/minute.
First, save a file on your system which has the same contents as this. Name it any way, for example paper_items.json.
Now make a file named checkitems.php. Read the file which changes frequently, compare if it's contents are equal to your paper_items.json. If equal, nothing to do, if not, save the online file to your local paper_items.json and use PHP's mail() to email you something like "there was a change".
Finally, set up a cron job to run this every n (for example 1) hour or 1 minute, etc.