Posted By

hasantayyar on 07/17/09


Tagged

php twitter


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

maxvee8
jealousy
irishsk
legacye
nb109
mprough


Using Twitter for sending server downtime alert


 / Published in: PHP
 

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

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

  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. curl_close($ch);
  20.  
  21. // Are things in right place ?
  22. if ($response == $targetText) {
  23. die('Site is up and running!');
  24. }
  25.  
  26. // Nope, so here are the sender's twitter info
  27. $username = 'SENDER_TWITTER_USERNAME';
  28. $password = 'SENDER_TWITTER_PASSWORD';
  29.  
  30. // Receiver's twitter username
  31. $receiver = 'RECEIVER_TWITTER_USERNAME';
  32.  
  33. // Alert message to send
  34. $message = 'Daredevil is not responding, please fix ASAP!';
  35.  
  36. // The Twitter API address (new direct message)
  37. $url = 'http://twitter.com/direct_messages/new.json';
  38.  
  39. // We will be using cURL for this
  40. $ch = curl_init();
  41.  
  42. // Set the params
  43. curl_setopt($ch, CURLOPT_URL, "$url");
  44. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
  45. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  46. curl_setopt($ch, CURLOPT_POST, 1);
  47. curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$receiver&amp;text=$message");
  48. curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
  49.  
  50. // Send the request
  51. $response = curl_exec($ch);
  52. curl_close($ch);
  53.  
  54. // Success or failure
  55. if (!empty($response)) {
  56. echo 'Recipient has been notified.';
  57. } else {
  58. echo 'No response from twitter.';
  59. }
  60. ?>

Report this snippet  

You need to login to post a comment.