Return to Snippet

Revision: 15803
at July 17, 2009 08:32 by hasantayyar


Initial Code
<?php

// Specify the target URL in your server
$targetUrl  = 'http://YOUR_SERVER_URL';

// Specify what the response is from the server
$targetText = 'Hello from Daredevil';

// We will be using cURL for fetching the content
$ch = curl_init();

// Set the params
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Get the response
$response = curl_exec($ch);
curl_close($ch);

// Are things in right place ?
if ($response == $targetText) {
    die('Site is up and running!');
}

// Nope, so here are the sender's twitter info
$username = 'SENDER_TWITTER_USERNAME';
$password = 'SENDER_TWITTER_PASSWORD';

// Receiver's twitter username
$receiver = 'RECEIVER_TWITTER_USERNAME';

// Alert message to send
$message = 'Daredevil is not responding, please fix ASAP!';

// The Twitter API address (new direct message)
$url = 'http://twitter.com/direct_messages/new.json';

// We will be using cURL for this
$ch = curl_init();

// Set the params
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$receiver&amp;text=$message");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

// Send the request
$response = curl_exec($ch);
curl_close($ch);

// Success or failure
if (!empty($response)) {
    echo 'Recipient has been notified.';
} else {
    echo 'No response from twitter.';
}
?>

Initial URL
http://www.phpfour.com/blog/

Initial Description
"Why I needed this?

Recently we have setup a server at our office for committing work to a local SVN repository and have the QA test our work whenever they are ready. We also have a staging server where we do SVN update from this repo. Now, for the last few days, I’ve found the local server to be off due to a few reasons - but every time I realized this at night when I am back home and can’t do anything to turn it on. So I thought about this Twitter alert which is sent to my cell phone immediately when the server goes offline.

Btw, if Twitter doesn’t send SMS to your country, don’t worry. Check out the excellent service at Twe2 that I’ve been using for a couple days.

Cheers!"

Initial Title
Using Twitter for sending server downtime alert

Initial Tags
php, twitter

Initial Language
PHP