In order to make sure that your website is always available to the public, you have to monitor it. In this tutorial, I'll show you how you can easily create a monitoring script that will check your website availability and send an email or sms alert to you if it isn't.
Maybe I’m stating the obvious, but the PHP script has to be on a different server than the one used for the website you’d like to monitor. If the script is hosted on the same server as your site, then it becomes pretty useless: In fact, if your server is down the script will not be able to run and will not let you know.
The best solution is of course a dedicated server, but a home server can be ok as well. Shared web hosting like those provided by Hostgator or WpWebHost have a low price, but most don’t allow you to set up cron jobs, so be careful if you plan to buy.
Please note that depending on your location and cellular phone provider, this part of the tutorial may not work.
The first part of this tutorial is to create the monitor script. Pick up your favorite text editor and create a file named monitor.php. The script is very simple: we only need two functions, one to test if a specific site is available, and the other to alert you by sending an email.
Paste the following in your monitor.php file:
01.function check($host, $find) {
02. $fp = fsockopen($host, 80, $errno, $errstr, 10);
03. if (!$fp) {
04. echo "$errstr ($errno)\n";
05. } else {
06. $header = "GET / HTTP/1.1\r\n";
07. $header .= "Host: $host\r\n";
08. $header .= "Connection: close\r\n\r\n";
09. fputs($fp, $header);
10. while (!feof($fp)) {
11. $str .= fgets($fp, 1024);
12. }
13. fclose($fp);
14. return (strpos($str, $find) !== false);
15. }
16.}
17.
18.function alert($host) {
19. mail('[email protected]', 'Monitoring', $host.' down');
20.}
21.
22.$host = 'www.domain.com';
23.$find = 'Domain';
24.if (!check($host, $find)) alert($host);
At this point of the tutorial, we have a working monitoring script, but we have to type http://mymonitoringserver.com/monitor.php in a web browser to check our website, which makes our script almost useless.
The solution to that problem is to create a cron task to make the server execute monitor.php every hour. Open a SSH console to your monitor server and type the following:
* * * * /usr/local/bin/php -q /htdocs/www/monitor.php