Too Cool for Internet Explorer

Twitter made easy – How to tweet with PHP with 19 lines of code   October 7th, 2009

This Code isn’t working any more since twitter changed their authentication method. i have no intend to adapt this code and hereby declare it obsolete.

You know the dilemma, you want to write a simple tweeting PHP script and have to mess around with the Twitter API.
With the following small script you can tweet with a simple function call. It IS that simple (And SSL secured!!!).

Here’s the function:

function tweet($user, $pass, $text) {
	unset($GLOBALS['tweetError']);
	if(strlen($text) > 140) { $GLOBALS['tweetError'] = 'TEXT TOO LONG: '.$text; return false; }
	$tweet = curl_init();
	curl_setopt($tweet, CURLOPT_URL, 'https://www.twitter.com/statuses/update.xml');
	curl_setopt($tweet, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($tweet, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($tweet, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($user.':'.$pass)));
	curl_setopt($tweet, CURLOPT_POST, 1);
	curl_setopt($tweet, CURLOPT_POSTFIELDS, 'status='.utf8_encode($text));
	if(!$return = curl_exec($tweet)) $GLOBALS['tweetError'] = 'CURL ERROR: '.curl_error($tweet);
	else if($returnData = simplexml_load_string($return)) {
		if(!isSet($returnData->error)) $GLOBALS['tweetSuccess'] = 'Created at: '.$returnData->created_at.'<br />Text: '.utf8_decode($returnData->text);
		else $GLOBALS['tweetError'] = 'TWITTER ERROR: '.$returnData->error;
	} else $GLOBALS['tweetError'] = 'RETURN IS NOT XML: '.$return;
	curl_close($tweet);
	return (isSet($GLOBALS['tweetError']))?false:true;
}

To make a tweet just call the function:

tweet("username", "password", "My cool tweet!");

The function returns “true” if successful or “false” if not.
To echo out the error or success messages, just use this code:

if(tweet("username", "password", "My cool tweet!")) {
	echo 'Tweet Successful!<br />'.$GLOBALS['tweetSuccess'];
} else {
	echo 'Tweet Error!<br />'.$GLOBALS['tweetError'];
}

If there was an error, the error description is saved in $GLOBALS['tweetError'], and if the tweet was successful, the time and the text itself is saved in $GLOBALS['tweetSuccess'].

Have fun and happy (automatic?) tweeting.

Tags: , , , , , ,
This entry was posted on Wednesday, October 7th, 2009 at 22:38 and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed.You can leave a response, or trackback from your own site.

No Responses

Leave a Reply