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:
- If there is already a cache file, present it. Else...
- Start PHP's output buffer
- Process your business logic and present the XHTML
- Store the buffer as a cache file
- 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 |
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