文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Page caching in PHP

Page caching in PHP

时间:2010-06-13  来源:yueming

Some web sites and applications have complex ways of parsing and manipulating data before the information is presented to the visitor or user. This article addresses the need for page caching, a way of processing the information once and caching the page's content for any subsequent views. I'm writing this article in view of providing page caching for simple CMSs (Content Management Systems). The key points for processing page caching are as follows:

  1. If there is already a cache file, present it. Else...
  2. Start PHP's output buffer
  3. Process your business logic and present the XHTML
  4. Store the buffer as a cache file
  5. Output the contents of the buffer to the screen

So, with all of that said and done let's look at the code to perform this functionality:

 

// The name and path for the cache file
$cache_file_directory = "/home/username/public_html/cache/";
$cache_filename = $cache_file_directory . __FILE__ . ".cache";

// If the cache file exists, present it
if(file_exists($cache_filename))
{
    $file_handle = fopen($cache_filename, "r");
    echo fread($file_handle, filesize($cache_filename));
    fclose($file_handle);
}
else
{
    // Create a temporary swap file
    $swap_filename = $cache_file_directory . md5(getmypid());
    $swap_handle = fopen($swap_filename, "w");
    
    // Start the output buffer from here
    ob_start();
    
    /*** Process and render your web page here ***/

    // Write the contents of the output buffer to the swap file
    fwrite($swap_handle, ob_get_contents());
    fclose($swap_handle);

    // Rename the swap file to the final cache file name
    rename($swap_filename, $cache_filename);

    // Stop the output buffer and clear its contents
    ob_end_flush();
}


As you can see by the above code, the functionality to perform page caching is quite simplistic, although there are a few points to consider:

  • Make sure that the cache file directory is writable (chmod 777 in most cases)
  • To clear the cache all you have to do is delete the .cache files
  • If you update any information on your page then you must clear the cache
  • If the page is updated by your users or visitors then you must disable caching

One important point I would like to cover is to do with the way we use swap files to stop file write conflictions. This is necessary so that two simultaneous fopens do not cause the cache file to erroneously written if two visitors try to create a cache file at the same time

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载