PHP Site Monitor Script (with email alerts or text messages.)

<?php
// check list of URLs (select URLs with small traffic - static content)
url_test('http://www.fabiodemelo.com');
url_test('http://www.demelos.com');

//Email
//If you like to receive a text message check for the web. for example at&t will be number@txt.att.net.
function url_test($url, $email_admin='your@email.address'){
// set timeout
$timeout = 10;
// init url session and set curl options
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_TIMEOUT, $timeout);
$http_respond = curl_exec($ch); // execute http request
// remove all html tags from the http response
$http_respond = trim(strip_tags($http_respond));
// get status from the http response
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// returned http code should be 200 otherwise there is a problem
if ($http_code != 200){
// prepare tested server name (component parameter added in PHP 5.1.2)
$http_server = parse_url($url, PHP_URL_HOST);
// and who was tester
$hostname = trim(`/bin/hostname`);
// get an error message from the URL request
$http_error = trim(curl_error($ch));
// prepare e-mail message
$email_message = "TEST URL: $url";
if ($http_code) $email_message .= "\n\nHTTP CODE: $http_code";
if ($http_respond) $email_message .= "\n\nHTTP RESPOND:\n$http_respond";
if ($http_error) $email_message .= "\n\nHTTP ERROR:\n$http_error";
// prepare e-mail header
$email_header = "Content-Type: text/plain; charset=\"iso-8859-2\"\n".
"Subject: http://$http_server problem!\n".
"From: monitor@$hostname\n".
"X-Priority: 1\n".
"Priority: Urgent\n".
"Importance: high";
// send e-mail message
error_log($email_message, 1, $email_admin, $email_header);
}
// close url session
curl_close($ch);
}
?>

I run monitor script every five minutes and here is my cron entry:

# PHP Web server monitor
*/5 * * * * /usr/bin/php /usr/local/scripts/monitor.php
This entry was posted in Code Examples, PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


4 + = 13

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>