RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Simple Cache With PHP

Simple Cache With PHP

It was on May 4th, 2011 that we published an article on Internoetics titled "Cache Your Website with PHP (in 1 minute)". Now redirecting to this post, the former article was aimed at caching an entire webpage with a function not that different than what is described here. The problem, however, is that if you're going to cache an entire site, there's far better ways of doing so than what we had previously described. While we'll republish the (updated) original code soon, the purpose of this article supplies functions designed to cache small amounts of dynamic data - not an entire page.

In the course of publishing WordPress shortcode in the past, we almost always utilized the framework's transient features... but naked PHP code generally went without caching - despite desperately needing it. For that reason, as we migrate code over from a plethora of our other websites, we'll reference a very basic PHP caching function that isn't entirely dissimilar to WP's transient API.

About Simple Cache (and WP's Transient API)

The principle of the WordPress transient API is simple: it offers a simple and standardized way of storing cached data in a database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted. Our PHP functions emulate this behaviour for use outside of WP (used mainly for our PHP code snippets that require a cache feature).

Why cache data? Caching transient or temporary data is useful when querying rate-limited third-party APIs that provide living and evolving information (such as RSS and news feeds, social counts, your last tweet, currency conversions, interest rates, weather forecasts etc). The idea is that you request data, store it for a particular time period, and then query new data when your defined cache interval has expired. The time period you'll cache data is usually determined by the API itself, the frequency at which data is updated, or perhaps the time it takes to process new information.

The primary difference between our functions compared to that of WordPress is that we'll cache data in a text file - not a database. Keep in mind that our solution is intended to be used outside of WordPress... so if you're using WP, continue to use the transient API.

Simple Cache With PHP

Our functions will store cached data in text files.

The PHP functions below are designed to emulate WP's get_transient() and set_transient() functions. They'll be referenced over and over for future PHP functions we share on our blog. They're also extremely simple so you can expect them to evolve in a serious way over time.

beliefmedia_set_transient

Not unlike WordPress' set_transient function, our simple beliefmedia_set_transient function works in a similar manner. It takes the unique transient name and the data you wish to cache and writes it to a text file in a defined directory. Like WordPress, we'll serialize the data if it's an array.

1
<?php 
2
/*
3
 Simple Cache With PHP
4
 http://www.beliefmedia.com/simple-php-cache
5
 http://shor.tt/1P7C
6
*/
7
 
8
function beliefmedia_set_transient($transient, $data) {
9
 
10
  /* You must define a location for your cache directory.. */
11
  $location = '/path/to/public_html/your/cache/' . $transient . '.txt';
12
 
13
  /* If the data is an array, we'll serialize it */
14
  if (is_array($data)) $data = serialize($data);
15
 
16
  /* Write string or serialized array to text file */
17
  $fp = @fopen($location, 'w');
18
  $result = fwrite($fp, $data);
19
  fclose($fp);
20
 
21
 return ($result !== false) ? true : false;
22
}

Note that you'll have to define a location for your cache directory.

beliefmedia_get_transient

The beliefmedia_get_transient function is intended to emulate the WordPress get_transient function (with the exception that we'll also provide the cache value as an argument in addition to the transient name). The function simply checks the creation time of the cached file against the current time and cache value. If it's valid we'll return the data; if not, we'll return the boolean false. Not unlike WordPress, we'll unserialize the data if required (in fact, we use a WordPress function to check).

1
<?php 
2
/*
3
 Simple Cache With PHP
4
 http://www.beliefmedia.com/simple-php-cache
5
 http://shor.tt/1P7C
6
*/
7
 
8
function beliefmedia_get_transient($transient, $cache = '21600') {
9
 
10
  /* You must define a location for your cache directory.. */
11
  $location = '/path/to/public_html/your/cache/' . $transient . '.txt';
12
 
13
  /* If the file exists and it hasn't expired, we'll return data, otherwise false */
14
  if ( file_exists($location) && (time() - $cache < filemtime($location)) ) {
15
 
16
    $result = @file_get_contents($location);
17
    if (beliefmedia_is_serialized($result) === true) $result = unserialize($result);
18
 
19
    /* Will return false anyhow... */
20
    return ($result) ? $result : false;
21
 
22
  } else {
23
 
24
    return false;
25
 
26
  }
27
}

Note that you'll have to define a location for your cache directory.

beliefmedia_is_serialized

To determine if the cached data is serialized before it's returned, we use WordPress' is_serialized() function (we've prefixed it with beliefmedia to avoid any clashes, but it's otherwise unaltered). The function will return false if the data isn't serialized, otherwise it'll return true.

1
<?php 
2
/*
3
 Simple Cache With PHP : http://shor.tt/1P7C
4
 http://www.beliefmedia.com/simple-php-cache
5
 https://codex.wordpress.org/Function_Reference/is_serialized
6
 Returns boolean (false if not serialized and true if it was)
7
*/
8
 
9
function beliefmedia_is_serialized( $data ) {
10
    // if it isn't a string, it isn't serialized
11
    if ( !is_string( $data ) )
12
        return false;
13
    $data = trim( $data );
14
    if ( 'N;' == $data )
15
        return true;
16
    if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
17
        return false;
18
    switch ( $badions[1] ) {
19
        case 'a' :
20
        case 'O' :
21
        case 's' :
22
            if ( preg_match( &quot;/^{$badions[1]}:[0-9]+:.*[;}]\$/s&quot;, $data ) )
23
                return true;
24
            break;
25
        case 'b' :
26
        case 'i' :
27
        case 'd' :
28
            if ( preg_match( &quot;/^{$badions[1]}:[0-9.E-]+;\$/&quot;, $data ) )
29
                return true;
30
            break;
31
    }
32
    return false;
33
}

Caching Options

We expect that we'll publish WordPress shortcodes that utilize the Options API . It's likely we'll make a similar set of PHP functions available that emulate the same features when it becomes necessary.

An advantage of storing data in text files means that if the data is expired, and a request for new information fails, you can simply request the old information and note its (older) creation time (essentially providing an option without the expiration feature). Something like this will simply return existing data (or return false if it doesn't exist).

1
<?php 
2
/*
3
 Simple Cache With PHP http://shor.tt/1P7C
4
 http://www.beliefmedia.com/simple-php-cache
5
 Returns existing data (as an option)
6
*/
7
 
8
function beliefmedia_get_transient_data($transient) {
9
 
10
  /* You must define a location for your cache directory.. */
11
  $location = '/path/to/public_html/your/cache/' . $transient . '.txt';
12
 
13
  /* Get the data & creation time */
14
  if (file_exists($location)) {
15
 
16
    $data = file_get_contents($location);
17
    if (beliefmedia_is_serialized($data) === true) $data = unserialize($data);
18
    return $data;
19
 
20
  } else {
21
 
22
    return false;
23
 
24
  }
25
}

If you chose to include the data's creation time (handy if you're returning data which is quite old), simply apply the following:

1
<?php 
2
/*
3
 Simple Cache With PHP http://shor.tt/1P7C
4
 http://www.beliefmedia.com/simple-php-cache
5
 Returns data creation time
6
*/
7
 
8
function beliefmedia_get_transient_time($transient) {
9
 
10
  /* You must define a location for your cache directory.. */
11
  $location = '/path/to/public_html/your/cache/' . $transient . '.txt';
12
 
13
  /* Get creation time : http://php.net/manual/en/function.date.php */
14
  $creation_time = date('jS F g:ia', filemtime($location));
15
 
16
 return $creation_time;
17
}

Considerations

  • If you were to store information in a database rather than text files, you could quite easily alter the function so it more closely resembled WordPress' transient API.
  • It should be noted (again) that the primary purpose of our functions were to make very basic cache functions available that can be referenced when sharing our PHP code snippets.
  • Note that we define $location = '/path/to/public_html/your/cache/' . $transient . '.txt'; in each function. If you're using a configuration file or similar, define this path here and alter the code as necessary.

Update, 1st June 2017: We've created a WordPress plugin. Simply upload and activate. A few of our plugins now require it be installed.

Video Introduction

Download


Title: Simple PHP Cache
Description: Simple PHP cache. Emulates WP's get_transient and set_transient functions.
  Download • Version 0.2, 2.6K, zip, Category: WordPress Plugins (General)

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment