Skip to content

Instantly share code, notes, and snippets.

@Ahrengot
Created June 19, 2012 19:37
Show Gist options
  • Save Ahrengot/2956092 to your computer and use it in GitHub Desktop.
Save Ahrengot/2956092 to your computer and use it in GitHub Desktop.
twitter-proxy.php
<?php
$query = $_GET["q"];
if (!isset ($query)) echo 'NO QUERY PASSED TO TWITTER PROXY';
$cache = dirname(__FILE__) . '/cache/twitter-' . urlencode($query) . '.txt';
// How long we'll allow the cached file to live.
$cacheDur = 60 * 3;
// Check if cached file exist and if it's older than a specific number of seconds
// (1 hour is 3.600 seconds)
if (!file_exists($cache) || filemtime($cache) < (time() - $cacheDur)) {
$result = file_get_contents('http://search.twitter.com/search.json?q=' . urlencode($query), true);
// Cached data either didn't exist or was to old. Let's (re)create it.
// 'wb' supposedly means write binary. It's not documented in the php docs here: http://php.net/manual/en/function.fopen.php
// Read more about 'wb' here: http://stackoverflow.com/questions/3824051/why-does-my-server-keep-creating-new-files-with-0640-permissions-in-my-php-fwrite
$cachefile = fopen($cache, 'wb');
fwrite($cachefile, $result);
fclose($cachefile);
}else {
// Cached text file with tweet data exists and isn't too old so just load that
$result = file_get_contents($cache);
}
// Right now our tweets data is just one big string, so let's decode it into JSON
echo $result;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment