PHP Twitter Caching Like a Champ

Easily cache multiple pages of Twitter API JSON responses. See how to expand on the StackOverflow solution to save time and improve performance.


When I started working on a Twitter intelligence app I needed a way to cache multiple pages of JSON responses from the Twitter API. I found a partial solution on StackOverflow but it only enabled caching for 1 page. I wanted caching for multiple pages (e.g. 1,2,3,4 etc.).

Server code binary etherial

I setup essentially 3 PHP pages.

  • A JSON PHP page echoes the JSON that I handle via a jQuery front-end page with AJAX.
  • A cache function page that checks and handles the caching.
  • A twitter_connection page that handles the authentication and Twitter API connection (I didn’t code that).

The cache lasts for 50 minutes. It gets written to disk and for each page gets added to an array that eventually get serialized. If there have been no requests in the last hour, the entire cache gets removed and starts fresh with the latest page request. This keeps the file size small.

I setup a cache folder at the root of my site.

PHP JSON Generation Page

$apiURL = "https://api.twitter.com/1.1/users/search.json?q=".$q."&count=".$numtweets."&page=".$page."&include_entities=false";
			$tweets = cacheCheck($apiURL,"twitter_users");

Cache.php page

function cacheCheck($apiURL,$type) {

$cacheFile = dirname(__DIR__).'/cache/'.$type.'.data';

	if (file_exists($cacheFile)) {
		$data = unserialize(file_get_contents($cacheFile));
		if ($data[$apiURL.'_timestamp'] > time() - 50 * 60) {
			$twitter_result = $data[$apiURL];
		}
	}

if (!$twitter_result) { // cache doesn't exist or is older than 50 mins
	require_once("twitter_connection.php");

	// gather other data to append
	if (file_exists($cacheFile)) {
		$otherData = unserialize(file_get_contents($cacheFile));
		if($otherData['cache_updated'] < time() - 60 * 60) unset($otherData); // clear whole cache after 1 hour		 	} 	$twitter_result = $connection->get($apiURL);

	$data = array ($apiURL => $twitter_result, $apiURL.'_timestamp' => time()); // each page gets its own key / value

	if(isset($otherData)) $data = array_merge($data,$otherData);

	$data['cache_updated'] = time();

	try {
	$numChars = file_put_contents($cacheFile, serialize($data));
	if(!$numChars)die("file put failed : ". $cacheFile);
}
	catch (Exception $e) {
	    die('Caught exception: '.$e->getMessage());
	}

}

return $twitter_result;

}