Using Twitter for sending server downtime alert


/ Published in: PHP
Save to your folder(s)

"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!"


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. // Specify the target URL in your server
  4. $targetUrl = 'http://YOUR_SERVER_URL';
  5.  
  6. // Specify what the response is from the server
  7. $targetText = 'Hello from Daredevil';
  8.  
  9. // We will be using cURL for fetching the content
  10. $ch = curl_init();
  11.  
  12. // Set the params
  13. curl_setopt($ch, CURLOPT_URL, $targetUrl);
  14. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
  15. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  16.  
  17. // Get the response
  18. $response = curl_exec($ch);
  19.  
  20. // Are things in right place ?
  21. if ($response == $targetText) {
  22. die('Site is up and running!');
  23. }
  24.  
  25. // Nope, so here are the sender's twitter info
  26. $username = 'SENDER_TWITTER_USERNAME';
  27. $password = 'SENDER_TWITTER_PASSWORD';
  28.  
  29. // Receiver's twitter username
  30. $receiver = 'RECEIVER_TWITTER_USERNAME';
  31.  
  32. // Alert message to send
  33. $message = 'Daredevil is not responding, please fix ASAP!';
  34.  
  35. // The Twitter API address (new direct message)
  36. $url = 'http://twitter.com/direct_messages/new.json';
  37.  
  38. // We will be using cURL for this
  39. $ch = curl_init();
  40.  
  41. // Set the params
  42. curl_setopt($ch, CURLOPT_URL, "$url");
  43. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
  44. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  45. curl_setopt($ch, CURLOPT_POST, 1);
  46. curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$receiver&amp;text=$message");
  47. curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
  48.  
  49. // Send the request
  50. $response = curl_exec($ch);
  51.  
  52. // Success or failure
  53. if (!empty($response)) {
  54. echo 'Recipient has been notified.';
  55. } else {
  56. echo 'No response from twitter.';
  57. }
  58. ?>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.