Support:

Skip special feature

Where's Simon?

Language selection:

English Deutsch

Using Twitter with PHP

1. Preface

Twitter is a well known social networking and micro-blogging online service that enables its registered users to send and read short messages of up to 140 characters in length. These messages are also known as tweets.

The user's updates are displayed on his own profile page at twitter.com and are delivered to other users who have signed up to receive them (in this case they 'follow' the user). Updates can be made using the given webinterface on the named website, using one of the gateway SMS numbers or using other third party applications like browser plug-ins, online services, widgets and so on.

All third party implementations are based upon a well documented API that enables programmers to integrate Twitter functionalities into all kinds of applications easily.

Several millions of users and companies are already using Twitter every day to communicate or exchange information. More and more websiteowners, -users and webdevelopers feel a growing need to update and display their tweets from own websites or content management systems without the hazzle of dealing with additional software or the official Twitter website.

This is why I started a comprehensive sample implementation of Twitter services in the common langauge PHP. The result is a well standardized PHP class that can be downloaded below. It should keep your head free for more important work, you will be able to use the most important Twitter functionalities in your own PHP application by including just one file and adding some lines of code.

2. System requirements

In order to use this PHP-class, your server needs to run PHP at least in version 5.2 including the cURL-library.

PHP installations below version 5.2 won't be able to utilize this class as up-to-date functions like filter_var and the PHP 5 object model are used which are not supported in earlier versions. There are no plans to establish downwards compatibility with PHP 4.x servers as the support for PHP 4 has been discontinued since December 2007.

Please bear in mind that all in- and outputs are handled in UTF-8. This may cause problems if you use this class in combination with applications that feature another encoding. You will have to encode or decode data in these cases.

3. License

This class is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This class is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

4. Download

All information and sourcecode related to this project can be found at the regarding projectpage at Sourceforge.net.

Please download the latest release and extract all the zipfile contents into the regarding directory of your webapplication on your webserver.

5. Installation

The first step to use the Twitter class in your PHP-application is to include the classfile itself (dependant on your installation, you probably will have to adjust the contained filepath):

require_once('twitter.php');

Next, you will have to create a new object or use an already existing object instance with the method getInstance (this implementation is based upon a singleton pattern):

$Twitter = Twitter::getInstance();

In order to work with Twitter, you need to provide the userdata of your Twitter-account:

$Twitter->setUser('yourUsername','yourPassword');

6. Functionalities

Now you are ready to post a tweet. The regarding method is called post():

$Twitter->post('This is a new tweet!');

This method expects a string formatted parameter (which is limited to 140 characters) that will be posted to Twitter and will return boolean true in case of a successful posting or a string formatted message in case of occuring errors.

To delete one of your tweets that already has been posted, you need to know its ID (which can be retrieved using the methods below). The regarding method is called deletePost():

$Twitter->deletePost(idOfDesignatedTweet);

This method expects an integer parameter containing the post-ID and will return boolean true in case of a successful posting or a string formatted message in case of occuring errors.

To follow or unfollow another user on Twitter, you just have to call one of the methods below:

$Twitter->followUser('designatedUsername');

$Twitter->unfollowUser('designatedUsername');

Both methods will return boolean true in case of success or a string formatted errormessage in case of occuring errors.

You may want to retrieve detailed data of one single Twitter user. This can be done using the method getUser():

$Twitter->getUser('designatedUsername');

This method expects a string parameter either containing the username or Twitter-ID of the designated user and will return an array with all available userdata or a string formatted message in case of occuring errors.

Of course, there is also a method to retrieve detailed information about one single tweet. It is called getPost():

$Twitter->getPost(idOfDesignatedTweet);

This method expects an integer parameter containing the post-ID and will return an array with all available postdata or a string formatted message in case of occuring errors.

The current implementation also features 3 methods for retrieving userlists:

$Twitter->getFriends();

$Twitter->getFollowers();

$Twitter->getFeaturedUsers();

getFriends() and getFollowers() are related to the user that has been set by setUser(), getFeaturedUsers() will return a list that is arranged by Twitter itself.

All of these methods return an array containing a list of users including some userdetails and the latest post of each user or a string formatted message in case of occuring errors.

Another important figure when working with Twitter are timelines. You may use the following 4 methods for retrieving them:

$Twitter->getMentions(optionalIntegerAmountOfRequiredItems);

$Twitter->getUserTimeline(optionalIntegerAmountOfRequiredItems);

$Twitter->getFriendsTimeline(optionalIntegerAmountOfRequiredItems);

$Twitter->getPublicTimeline();

Again, getMentions(), getUserTimeline() and getFriendsTimeline() are related to the user that has been set by setUser() while getPublicTimeline() will return a tweetlist that is arranged by Twitter itself.

All of these methods return an array containing a list of the last 20 tweets of related users including some userdetails or a string formatted message in case of occuring errors. If you should need more or less than 20 items, the first 3 methods are able to return a specific amount of items if you call them using the optional integer parameter (please be aware that there is a maximum limit of 200 items).

7. Extending this class

If you should require more than the provided functionalities of this class, you should extend it with another PHP-class rather than patching the file. This will help you staying up to date when new versions of this class will be released.

You may use all of the described methods within your extending class as they have public access rights granted. In addition to that, there is a protected method for checking if the usercredentials already have been set:

$Twitter->validateUserdata();

It will return a boolean value that can help you to improve the Twitter workflow within your own application by providing the information if a user already has been set.

The protected classvariable

$Twitter->maxPostLength;

contains the maximum amount of characters that is allowed for posting messages to Twitter. You could use this property for creating a validation procedure for message input forms. This will help you staying up to date in case that Twitter will change this property in the future.

8. Additional notes

All provided methods of this class that are designed to retrieve information from Twitter have an implemented mechanism for filtering the returned contents. The contents are verified, sanitized and are returned in their correct datatype. This will help you to improve application security and will save some performance when working with returned datasets.

Information that is provided by Twitter also contains timestamps. This class will convert every originally available timestamp into a standardized UNIX-format to simplfy the usage of the returned datasets in PHP.

9. Twitter limitations

Twitter imposed reasonable limits to help prevent system and user abuse:

  • 1000 updates per day
  • 1000 direct messages per day
  • 100 API requests per hour
  • Follow limit

Twitter does not limit the number of people who can follow you, but they have put limits in place to stop people from aggressively following others. Everyone is allowed to follow 2000 people. After that, follow limits are based on the number of people who are following you.

Follow limits cannot be lifted by Twitter and everyone is subject to follow them, even high profile and API accounts.

Please make sure that you use this PHP class reasonably and try to avoid unneccessary requests.

For more information, please see this Twitter support article.

10. Changes and updates

Changes that are applied to this software are documented in the file changelog.txt that is included within within the directory "/docs" of the provided zip-archive.

New versions of this class will always be available on the regarding projectpage at Sourceforge.net. This platform will also provide you with news about ongoing work and future releases.

Please feel free to contact me for feature requests or in case of emerging errors or bugs.



copyright © 2002-2010 by Simon Wippich, all rights reserved.

Back to the top of this page