Quick Tip: How to Cache Data 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:
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:
$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:
$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:
$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.
Share This Article
Cláudio Ribeiro is a software developer, traveler, and writer from Lisbon. He’s the author of the book An IDE Called Vim. When he is not developing some cool feature at Kununu he is probably backpacking somewhere in the world or messing with some obscure framework.
How do I cache a web page in PHP?
how do I cache a web page in php so that if a page has not been updated viewers should get a cached copy? Thanks for your help. PS: I am beginner in php.
you might want to consider moving it to a framework. code.google.com/p/samstyle-php-framework — full fledged framework that includes file caching and supports memcache
6 Answers 6
You can actually save the output of the page before you end the script, then load the cache at the start of the script.
else < unlink($cachefile); >ob_start(); // all the coding goes here $c = ob_get_contents(); file_put_contents($cachefile, $c); ?>
If you have a lot of pages needing this caching you can do this:
at the start of your scripts. and add
at the end of your scripts. Remember to have a folder named cache and allow PHP to access it.
Also do remember that if you’re doing a full page cache, your page should not have SESSION specific display (e.g. display members’ bar or what) because they will be cached as well. Look at a framework for specific-caching (variable or part of the page).
check the updated post. you can put the code into seperated php files and include them. remember — Don’t Repeat Yourself (DRY) policy.
@mauris : an answer below suggests it should be file_put_contents($cachefile,$c) (with the extra $c parameter). Can you confirm/deny?
@mwfearnley it’s been 13 years, I haven’t coded in PHP since at least 10 years ago. I doubt I’ll recommend my answer as the method to cache output, but it’s a basic PHP idea that’s possible. thanks for catching this.
Additionally to mauris answer I’d like to point this out:
You have to be careful when you use caching. When you have dynamic data (which should be the case when you use php instead of static html) then you have to invalidate the cache when the corresponding data changes.
This can be pretty easy or extremely tricky, depending on your kind of dynamic data.
How you invalidate the cache depends on the concrete kind of caching. You have to know which cache files belong to which page (and maybe with user input). When the data changes you should delete the cached file or remove the page output from your cache data structure.
I can’t give you any more detailed info about that without knowing which implementation you use for caching.
Other folks suggested for example the Pear package or memcached. These have the necessary functions to invalidate the whole cache or parts of it when data changes.