Quick Tip: How to Cache Data in PHP

    Claudio Ribeiro
    Share

    In this quick tip, we’ll talk about what caching is and how we can use it in PHP.

    It’s crucial to focus on performance when developing PHP apps. Web apps can have thousands or even millions of users, which can lead to slow performance and availability issues. Caching is invaluable in this respect, as it can help avoid performance pitfalls.

    What is Caching?

    Caching is a way to store frequently accessed data in a temporary storage location to reduce the number of times the data needs to be retrieved from its original storage location. This can greatly improve the performance of a website or application, as accessing data from cache is generally much faster than accessing it from its source.

    PHP provides several ways to implement caching. Let’s have a look at each of them.

    Output Buffering

    Output buffering is a technique in PHP that allows us to store the output of a PHP script in a buffer, rather than sending it directly to the browser. This allows us to modify the output or perform other actions on it before it’s displayed to the user.

    To start an output buffer, we can use the ob_start() function. This function will turn output buffering on and begin capturing all output sent by the script. The output can then be stored in a variable using the ob_get_contents() function. Finally, the output buffer can be ended and the output can be sent to the browser using the ob_end_flush() function, or it can be discarded using the ob_end_clean() function.

    Here’s an example of how output buffering works:

    <?php
    ob_start(); // Start the output buffer
    
    echo 'This output will be stored in the buffer';
    
    $output = ob_get_contents(); // Get the contents of the output buffer
    ob_end_clean(); // End the output buffer and discard the contents
    
    echo 'This output will be sent to the browser';
    

    In this particular example, the string 'This output will be sent to the browser' will be echoed only once, since we’re discarding the contents of the output buffer that contains the first echo instruction.

    Output buffering can be used as cache, as it allows us to store the output of a PHP script in memory, rather than generating it every time the script is accessed.

    Caching Functions

    PHP provides several functions specifically for caching data, including apc_store(), memcache_set(), and xcache_set(). These functions can be used to store data in memory, which can be accessed much faster than data stored on a hard drive.

    apc_store()

    The apc_store() function is part of the Alternative PHP Cache (APC) extension, which provides an opcode cache for PHP. (Opcode cache is a performance optimization technique for PHP that caches the compiled bytecode of PHP scripts in memory, rather than re-parsing and re-compiling the source code on each request.) It stores a value in the APC cache with a specified key and expiration time.

    Here’s an example of how to use the apc_store() function to cache a value in memory:

    <?php
    $value = 'This is the value to cache';
    
    // Store the value in cache for one hour
    apc_store('cache_key', $value, 3600);
    

    To retrieve the cached value, we can use the apc_fetch() function:

    <?php
    $cachedValue = apc_fetch('cache_key');
    
    if ($cachedValue) {
        // Use the cached value
        echo $cachedValue;
    } else {
        // Generate the value and store it in cache
        $value = 'This is the value to cache';
        apc_store('cache_key', $value, 3600);
        echo $value;
    }
    

    More information on apc_store() can be found here.

    memcache_set()

    The memcache_set() function is part of the Memcache extension, which allows you to use a Memcache server as a cache for PHP. It stores a value in the Memcache server with a specified key and expiration time.

    More information on memcache_set() can be found here.

    xcache_set()

    The xcache_set() function is part of the XCache extension, which provides a PHP opcode cache and data cache. It stores a value in the XCache cache with a specified key and expiration time.

    More information on xcache_set() can be found here.

    Caching with a Database

    Another option for caching in PHP is to use a database to store cached data. This may seem counterintuitive, as the primary goal of caching is to reduce the number of database accesses and improve performance. However, there are some cases where caching data in a database might be useful.

    One such case is if you need to cache large amounts of data that might not fit in memory. Additionally, caching data in a database can be useful if you need to access the cached data from multiple servers, as it allows for easy sharing of cached data between servers.

    To cache data in a database, you can use a table with at least two columns: one for the cache key, and one for the cached data. You can then use a SELECT query to check if the cache key exists in the table, and an INSERT or UPDATE query to store the data in the table.

    Here’s an example of how to cache data in a MySQL database:

    <?php
    $db = new mysqli('localhost', 'username', 'password', 'database');
    
    $cacheKey = 'cache_key';
    $cachedValue = 'This is the value to cache';
    
    // Check if the cache key exists in the table
    $result = $db->query("SELECT * FROM cache WHERE cache_key = '$cacheKey'");
    if ($result->num_rows > 0) {
        // Update the cached value
        $db->query("UPDATE cache SET value = '$cachedValue' WHERE cache_key = '$cacheKey'");
    } else {
        // Insert a new cache row
        $db->query("INSERT INTO cache (cache_key, value) VALUES ('$cacheKey', '$cachedValue')");
    }
    
    // Retrieve the cached value
    $result = $db->query("SELECT * FROM cache WHERE cache_key = '$cacheKey'");
    $row = $result->fetch_assoc();
    $cachedValue = $row['value'];
    
    echo $cachedValue;
    

    This example demonstrates how to check if a cache key exists in the cache table, and if it does, how to update the cached value. If the cache key doesn’t exist, a new row is inserted into the table with the cache key and value. The cached value is then retrieved from the table and displayed to the user.

    Conclusion

    Caching is a very powerful technique for improving the performance of a PHP website or application. PHP provides several options for implementing caching, including output buffering, caching functions, and caching with a database. By storing frequently accessed data in a temporary location, we can reduce the number of times the data needs to be retrieved from its source and improve the overall speed and performance of a site.