Return to Snippet

Revision: 15615
at July 11, 2009 23:52 by DrewDouglass


Initial Code
// (C) Copyright JAMES PADOLSEY
class tweetFromFile {
 
    private $curlHandle;
    private $updateFile;
    private $archiveFile;
 
    private function getNewStatus() {
 
        $upcomingTweetsFile = $this->files['upcoming'];
        $archivedTweetsFile = $this->files['archive'];
 
        $upcomingTweets_R = fopen($upcomingTweetsFile, "r");
 
        // Get upcoming Tweets:
        $contents = fread($upcomingTweets_R, filesize($upcomingTweetsFile));
        $splitContents = preg_split('/\n/', $contents, 2);
 
        // ARCHIVE OLD POSTS:
        $archive = fopen($archivedTweetsFile, "a");
        fwrite($archive, $splitContents[0]."\n");
 
        // Remove top line from upcoming:
        $upcomingTweets_W = fopen($upcomingTweetsFile, "w");
        fwrite($upcomingTweets_W, $splitContents[1]);
 
        // Clean up
        fclose($upcomingTweets_W);
        fclose($upcomingTweets_R);
        fclose($archive);
 
        return $splitContents[0];
    }
 
    public $files = array('upcoming' => '', 'archive' => '');
 
    public function __construct($username, $password, $filename) {
 
        $this->curlHandle = curl_init();
        $this->files['upcoming'] = $filename;
        $this->files['archive'] = 'ARCHIVE_' . $filename;
 
        // Shortcut:
        $ch = $this->curlHandle;
 
        curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/update.xml");
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
 
    }
 
    public function __destruct() {
        curl_close($this->curlHandle);
    }
 
    public function updateStatus() {
 
        $status = $this->getNewStatus();
 
        curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, "status=$status");
 
        $result = curl_exec($this->curlHandle);	
	$resultArray = curl_getinfo($this->curlHandle);
 
        if ($resultArray['http_code'] == 200) return true;
 
        return false;
 
    }
 
}
 
// ==================
// ===== USAGE ======
// ==================
 
$tweet = new tweetFromFile('twitterUsername', 'password', 'textfile.txt');
$success = $tweet->updateStatus();
if ($success) {
    echo 'Twitter updated!';
} else {
    echo 'Hmm, an error...';
}

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

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

Initial Title
Tweet From File Class

Initial Tags
class, php, twitter

Initial Language
PHP