Blog

A tiny PHP/Twitter script just for you!

Was rather bored this afternoon and then I though to myself "Why not add Twitter functionality to my music page?" So, after some digging through Twitter APIs and some refreshers on HTTP Authentication, I wrote this tiny, beautiful little script.

Code: php
  1. // Return values
  2. define ("TWITTER_OK", true);
  3. define ("TWITTER_UNAUTHORIZED", -1);
  4. define ("TWITTER_TOO_LONG", -2);
  5. define ("TWITTER_COULD_NOT_CONNECT", -3);
  6. function sendTweet ($status, $userName, $userPass)
  7. {
  8. // Open a socket to Twitter
  9. if (!($socket = fsockopen ("twitter.com", 80)))
  10. return TWITTER_COULD_NOT_CONNECT;
  11. // Create the headers
  12. $headers = "POST /statuses/update.xml HTTP/1.1\r\n";
  13. $headers .= "Host: twitter.com\r\n";
  14. $headers .= "Authorization: Basic ".base64_encode ($userName.":".$userPass)."\r\n";
  15. $headers .= "Content-length: ".strlen ("status=$status")."\r\n\r\n";
  16. $headers .= "status=$status\r\n";
  17. // Send the headers
  18. fwrite ($socket, $headers);
  19. // Get the response
  20. $response = "";
  21. while (!feof ($socket))
  22. $response .= fgets ($socket, 1024);
  23. // Check for HTTP status OK (200)
  24. if (!strpos ($response, "200"))
  25. return TWITTER_UNAUTHORIZED;
  26. return TWITTER_OK;
  27. }
  28. ?>

It is as simple as it looks. Enjoy!

Post A Comment

AvatarLogin with FacebookLogin with Twitter