Twitter TweeterJustin Poliey’s twitterlibphp is a great little object-orientated PHP interface to the Twitter API that makes whipping up Twitter-interfacing web applications a doddle. However, this short little tutorial is not about the library but rather about how to control where you are retrieving your twitter information from considering the fact that the makers of Twitter have installed an hourly request rate limit to ensure that the system’s servers don’t get overly abused by eager beaver script writers.

Needless to say, the way to play nicely then is to make use of a simple cache system, whereby you serve live data when you have remaining hits left for any particular hour (and generate a cache file while you are at it) or alternatively serve your cached snapshot of the data instead.

Now there are many ways to interface with twitterlibphp’s returned data, but for this mini-tutorial I’ll favour JSON, simply because of the compressed nature of its format. PHP comes with built in JSON functionality meaning that using it is pretty easy, but just a note, this support only comes standard from PHP 5.2.0 onwards.

So let’s spit out some commented code then shall we?

// require the twitter library

// initialize the twitter class
$twitter = new Twitter($twitter_name, $twitter_password);

// determine whether or not to use the cache or make live twitter service requests
// grab and decode the results from the rateLimitStatus call
$empty_array = array();
$jsondata = $twitter->rateLimitStatus($empty_array,’json’);
$json_object = json_decode($jsondata);

// intval the remaining hit to get an integer that we can use
$remaing_hits = intval($json_object->remaining_hits);
// variable to control which source we are using
$use_stream = ‘live’;

// if we’ve slipped to under ten remaining hits, use the cache
if ($remaing_hits < 10)
$use_stream = ‘cache’;

// just to indicate to you what source we are going use (as well as remaining hits)
echo “

$use_stream (Remaining: $remaing_hits)


// if stream is live, use the twitter lib to get fresh data. If not, use the cache file we’ve previously generated
case ‘live’:
$jsondata = $twitter->showUser($empty_array,’json’);
// hits are getting low, so let’s create/overwrite our cache file
if (($remaing_hits >= 10) && ($remaing_hits <= 20))
$ourFileName = ‘showUser.json’;
$ourFileHandle = fopen($ourFileName, ‘w’) or die(“can’t open cache file”);
fwrite($ourFileHandle, $jsondata);
case ‘cache’:
$ourFileName = ‘showUser.json’;
$ourFileHandle = fopen($ourFileName, ‘r’) or die(“can’t open cache file”);
$jsondata = fread($ourFileHandle, filesize($ourFileName));

// decode the retrieved account data
$json_object = json_decode($jsondata);

// just to display that we’ve got something
echo ‘

echo '


So there you go. A very simple little script but good enough to give you an idea on how to control your twitter information retrieval ideas.