matt hackmann -> web developer

A tiny PHP/Twitter script just for you!

Posted on in php twitter programming

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

It is as simple as it looks. Enjoy!

Add Comment

Sign-in with Twitter

To prevent the propagation of evil, evil spam, we require that you link your Twitter account with us. Don't worry, it's all legit and we're not storing any passwords or anything. Just to be safe, though, be sure to check the address bar after you click the "Sign in with Twitter" button and make sure that the address begins with https://twitter.com. If it doesn't, please contact me ASAP.