Skip to content

Instantly share code, notes, and snippets.

@rutger1140
Created March 13, 2014 18:38
Show Gist options
  • Save rutger1140/9534202 to your computer and use it in GitHub Desktop.
Save rutger1140/9534202 to your computer and use it in GitHub Desktop.
Very basic caching script for PHP
<?php
// Example usage
// Set source location
$sourcepath = "http://mysite.com/api/call/something";
// Set cache file
$cacheName = "apicall.cache";
// Set caching time
$ageInSeconds = 3600; // one hour
echo getCacheContent($cacheName, $sourcepath, $ageInSeconds);
<?php
/**
* Simple cache method
*
* @author: Rutger Laurman
* Based on http://stackoverflow.com/a/5263017
*/
function getCacheContent($cachefile, $remotepath, $cachetime){
// Toggle debug mode
$debug = false;
// Generate the cache version if it doesn't exist or it's too old!
if(file_exists($cachefile) && (filemtime($cachefile) > (time() - $cachetime))) {
if($debug){
echo "DEBUG: not expired, use cache\n";
}
} else {
if($debug){
echo "DEBUG: expired, attempt to refresh\n";
}
if($contents = @file_get_contents($remotepath)){
@file_put_contents($cachefile, $contents, LOCK_EX);
if($debug){
echo "DEBUG: refresh succes, cache written\n";
}
} else {
if($debug){
echo "DEBUG: refresh failed, using cache\n";
}
}
}
// Get contents of cache file
$fileContents = @file_get_contents($cachefile);
if($fileContents) {
return $fileContents;
} else {
if($debug){
echo "DEBUG: failed to get content";
}
}
}
@xeoncross
Copy link

I would at least pass a user agent so you don't get blocked by the remote host

<?php

function getCacheContent($cachefile, $remotepath, $cachetime){

    // Generate the cache version if it doesn't exist or it's too old!
    if( ! file_exists($cachefile) OR (filemtime($cachefile) < (time() - $cachetime))) {

        $options = array(
            'method' => "GET",
            'header' => "Accept-language: en\r\n" .
            "User-Agent: Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)\r\n"
        );

        $context = stream_context_create(array('http' => $options));
        $contents = file_get_contents($remotepath, false, $context);

        file_put_contents($cachefile, $contents, LOCK_EX);
        return $contents;
    }

    return file_get_contents($cachefile);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment