Saturday 31 August 2013

PHP Issue in Twitter API Caching Script

PHP Issue in Twitter API Caching Script

I admit I am a level below functional retardation when it comes to code
development of any sort. I'm trying to create a script that calls the
Twitter API and caches responses. I can call the API and get data without
issue, I can write it to a file too, and I can call the file to display
the info.
However, every time this piece of code is called, it results in a hit to
Twitter's API gateway. I can tell by reading the responses from a shell
window; this is on a busy site and I see the number of available
transactions decrease quickly when the script is made live.
Why isn't it delivering just info from the file, and running $tweets
everytime?
<?php
session_start();
require_once('/home/user/public_html/twitter_api/twitteroauth.php');
//Path to twitteroauth library
$twitteruser = "username";
$notweets = 3;
$consumerkey = "xyz";
$consumersecret = "xyz";
$accesstoken = "xyz";
$accesstokensecret = "xyz";
function getConnectionWithAccessToken($cons_key, $cons_secret,
$oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token,
$oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret,
$accesstoken, $accesstokensecret);
$tweets =
$connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$file = '/home/user/public_html/twitter_api/twitter_cache.data';
$cache_life = '900';
$filemtime = @filemtime($file);
if (!$filemtime or (time() - $filemtime >= $cache_life)){
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, serialize($tweets));
fclose($fh);
}
else
{
$twitter_result =
unserialize(file_get_contents('/home/user/public_html/twitter_api/twitter_cache.data'));
foreach ($twitter_result as $item) {
echo '<a href="http://twitter.com/username" target="_blank"
style="font-size:12px;">'.$item->text.'</a><br /><br />';
}
echo '<h5><a href="http://twitter.com/username" target="_blank"
class="tw">Follow On Twitter</a></h5>';
}
?>

No comments:

Post a Comment