Skip to Main Content

Implement Transparent File Caching for functions in PHP

Sometimes a script needs to call a function that either uses a large amount of system resources, or that performs external calls to servers or APIs that place limits on requests. Often, however, the data returned by these functions isn’t highly volatile, and can be expected to remain the same for subsequent calls.

In these cases, it is necessary to implement a form of cache, to store the results of running the function once, and use the same results on subsequent calls (clearing the cache regularly, to prevent buildup).


Caching to disk is fairly easy to implement in PHP, but it is nice to have a prebuilt, general purpose solution that can be dropped in to any project.

I’ve implemented a simple caching function below that will fit most needs. at the top of the file, there are a few configuration options that can be set, such as path to cache directory (which must be writable by php), whether cleaning the cache should be managed by the function or not (ideally, this would be handled by a separate cron job, but this is meant to be a simple all-in-one drop in solution), and what caps should be set on number of files and max size of cache.

Usage is fairly simple, too. Simply include the caching function, create a function that requires caching, and call the caching function with the name of the function, an optional array of the arguments being sent to the function, and an optional time to live for the cached file (in seconds)

For Example:

// include the cache function
// write your function that needs caching
function do_something_slow($argument1, $argument2) {
// do something slow, like a cURL request
// call your function via the cache function
$result = callFunctionWithCache("do_something_slow", array("arg1", "arg2"), 1800);

Here’s the cache function, in all it’s not that shiny glory:

Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>