Most content management systems and blogging platforms have a Twitter plug-in available nowadays that allows you to automatically submit tweets when you update a page or post a news item. However, for those of us that aren’t using packaged systems, we have to look elsewhere for solutions to post updates to Twitter.
The other day, while making some changes to the news posting script we use at work, I decided that we should post our news updates on Twitter when we post them to the Web site. As such, I started reviewing the Twitter API. Thankfully, Twitter has a good resource on libraries you can use to make your life easier (after all, there’s no point in reinventing the wheel if you don’t have to).
The one I chose is a PHP class simply called “Twitter.” The class is available from PHP Classes, a Web site chock full of various PHP classes, libraries and resources. Usage of the “Twitter” class could not be easier. All you do is include the class in your script, and then invoke a new instance of the “Twitter” class, providing your Twitter username and password. Within the constructor function of the Twitter class, the username and password are base64 encoded together with a colon in between, so you could conceivably rewrite the constructor function so that it simply accepts a base64 encoded string to begin with in order to provide a little more security.
Once you’ve invoked the Twitter class with your username and password, you simply call the “update” function of the new Twitter object you created, providing the text of the tweet you want to send. If there are any errors sending the tweet, the update function will return the text of that error. If the tweet gets posted successfully, the function returns boolean TRUE.
That’s all there is to it. When I started looking the other day, I had no idea it would be so simple.