How to Cache PHP Results
- 1). Open a text editor and create a new file. New files are typically created in text editors by selecting “New” from the “File” menu. Save the file as “php_cache.php” in a location on the Web server that has appropriate permissions.
- 2). Add two PHP delimiters to the file (“<?php” and “?>”). The PHP interpreter will interpret any text placed between the two delimiters as code.
<?php
?> - 3). Declare a PHP variable named “$fileCache”. Set the variable equal to the cache file’s name (the file that will hold the cached version of the page). Name the file “cache.html”.
$fileCache = "cache.html"; - 4). Check for the existence of “cache.html” on the server. If a version of cache.html exists, include (load) cache.html from the server and exit php_cache.php.
if (file_exists($fileCache))
{
include($fileCache);
exit;
} - 5). Turn on output buffering using the “ob_start” PHP function. While buffering is on, any output from php_cache.php will be stored in a buffer.
ob_start(); - 6). Use a PHP echo language construct to write an HTML header/title to the Web page. Because output buffering is on, this header will be written to the output buffer. To write the header, use an HTML “<h1>” tag, the text “Uncached Title” and close the “</h1>” tag.
echo "<h1>Uncached Title</h1>"; - 7). Use a PHP “fopen” function to bind cache.html to an output stream. Open the file in write mode (“w”) and set the output stream to a variable named “$fileOpen”.
$fileOpen = fopen($fileCache, 'w'); - 8). Use an “ob_get_contents” command to retrieve the contents of the output buffer. Use the PHP “fwrite” function to write the buffer’s contents to the $fileOpen output stream.
fwrite($fileOpen, ob_get_contents()); - 9). Use the PHP “fclose” function to close the $fileOpen output stream once the output buffer has been written. Cache.html now contains the buffer’s contents, or the “Uncached Title” written using the echo command.
fclose($fileOpen); - 10
Use the “ob_end_flush” function to flush and close the output buffer. After adding the function, php_cache.html will appear as shown below.
<?php
$fileCache = "cache.html";
if (file_exists($fileCache))
{
include($fileCache);
exit;
}
ob_start();
echo "<h1>Uncached Title</h1>";
$fileOpen = fopen($fileCache, 'w');
fwrite($fileOpen, ob_get_contents());
fclose($fileOpen);
ob_end_flush();
?> - 11
Open php_cache.html in a Web browser. If this is the first time php_cache.html has been opened, the HTML “<h1>Uncached Title</h1>” will display using PHP. If php_cache.html has been opened previously, the HTML “<h1>Uncached Title</h1>” will be read from cache.html.