Tweet From File Class


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

Thanks to James Padolsey for sharing this script with everyone on his blog, link above.


Copy this code and paste it in your HTML
  1. // (C) Copyright JAMES PADOLSEY
  2. class tweetFromFile {
  3.  
  4. private $curlHandle;
  5. private $updateFile;
  6. private $archiveFile;
  7.  
  8. private function getNewStatus() {
  9.  
  10. $upcomingTweetsFile = $this->files['upcoming'];
  11. $archivedTweetsFile = $this->files['archive'];
  12.  
  13. $upcomingTweets_R = fopen($upcomingTweetsFile, "r");
  14.  
  15. // Get upcoming Tweets:
  16. $contents = fread($upcomingTweets_R, filesize($upcomingTweetsFile));
  17. $splitContents = preg_split('/\n/', $contents, 2);
  18.  
  19. // ARCHIVE OLD POSTS:
  20. $archive = fopen($archivedTweetsFile, "a");
  21. fwrite($archive, $splitContents[0]."\n");
  22.  
  23. // Remove top line from upcoming:
  24. $upcomingTweets_W = fopen($upcomingTweetsFile, "w");
  25. fwrite($upcomingTweets_W, $splitContents[1]);
  26.  
  27. // Clean up
  28. fclose($upcomingTweets_W);
  29. fclose($upcomingTweets_R);
  30. fclose($archive);
  31.  
  32. return $splitContents[0];
  33. }
  34.  
  35. public $files = array('upcoming' => '', 'archive' => '');
  36.  
  37. public function __construct($username, $password, $filename) {
  38.  
  39. $this->curlHandle = curl_init();
  40. $this->files['upcoming'] = $filename;
  41. $this->files['archive'] = 'ARCHIVE_' . $filename;
  42.  
  43. // Shortcut:
  44. $ch = $this->curlHandle;
  45.  
  46. curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/update.xml");
  47. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
  48. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  49. curl_setopt($ch, CURLOPT_POST, 1);
  50. curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
  51.  
  52. }
  53.  
  54. public function __destruct() {
  55. curl_close($this->curlHandle);
  56. }
  57.  
  58. public function updateStatus() {
  59.  
  60. $status = $this->getNewStatus();
  61.  
  62. curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, "status=$status");
  63.  
  64. $result = curl_exec($this->curlHandle);
  65. $resultArray = curl_getinfo($this->curlHandle);
  66.  
  67. if ($resultArray['http_code'] == 200) return true;
  68.  
  69. return false;
  70.  
  71. }
  72.  
  73. }
  74.  
  75. // ==================
  76. // ===== USAGE ======
  77. // ==================
  78.  
  79. $tweet = new tweetFromFile('twitterUsername', 'password', 'textfile.txt');
  80. $success = $tweet->updateStatus();
  81. if ($success) {
  82. echo 'Twitter updated!';
  83. } else {
  84. echo 'Hmm, an error...';
  85. }

URL: http://james.padolsey.com/twitter/tweetfromfile-php-class/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.