PHP Cache Tool class implements Web caching

Source: Internet
Author: User
Tags browser cache

PHP Cache Tool class implements Web caching

When the PHP program is resistant to high-traffic access, dynamic sites are often difficult to parry, so introduce a caching mechanism that typically has two types of caches

First, the file cache

Second, the data query result cache, using memory to implement the cache

This example uses the file cache primarily.

The main principle is to use a cache function to store the results of a Web page, and if called again in a specified time, the cache file can be loaded.

Tool Class Code:

File Cache class/** * $dir: Cache file Directory * $lifetime: Cache file validity, in seconds * $cacheid: Cache file path, including file name * $ext: Cache file name extension (can not), here to make For easy */private $dir;p rivate $lifetime;p rivate $cacheid;p rivate $ext;/** * destructor to check if the cache directory is valid, default assignment */function __ Construct ($dir = ", $lifetime = 1800) {if ($this->dir_isvalid ($dir)) {$this->dir = $dir; $this->lifetime = $li Fetime, $this->ext = '. PHP '; $this->cacheid = $this->getcacheid ();}} /** * Check if the cache is valid */private function IsValid () {if (! file_exists ($this->cacheid)) return false;if (! (@ $mtime = Filemtime ($this->cacheid))) Return False;if (Mktime ()-$mtime > $this->lifetime) return False;return true; /** * Write Cache * $mode = = 0, get page content in browser cache * $mode = = 1 to direct assignment (received via $content parameter) to get page content * $mode = = 2, read locally (fopen Ile_get _contents) The way to get the page content (which seems not necessary in this way) */public function write ($mode = 0, $content = ") {switch ($mode) {case 0: $content = ob_ Get_contents (); break;default:break;} Ob_end_flush (); try {file_put_contents ($this-> CacheID, $content);} catch (Exception $e) {$this->error (' Write cache failed! Please check directory permissions! ');}} /** * Load Cache * EXIT () load cache and terminate the execution of the original page program, cache invalid run the original page program generated cache * Ob_start () Open browser cache to get page content at the end of the page */public function load () {if ($thi S->isvalid ()) {//two ways below, which way good????? Require_once ($this->cacheid); echo "<!--Cache--";//Echo file_get_contents ($this->cacheid); exit ();} else {Ob_start ();}} /** * Clear Cache */public function clean () {try {unlink ($this->cacheid),} catch (Exception $e) {$this->error (' Clear cache text Failed! Please check the directory permissions! ');}} /** * Get cache file path */private function Getcacheid () {return $this->dir. MD5 ($this->geturl ()). $this->ext;} /** * Check whether the directory exists or can create */private function Dir_isvalid ($dir) {if (Is_dir ($dir)) return true;try {mkdir ($dir, 0777);} cat CH (Exception $e) {$this->error (' Set cache directory does not exist and failed to create! Please check the directory permissions! '); return false;} return true;} /** * Get the current page full URL */private function Geturl () {$url = '; if (Isset ($_server [' Request_uri '])) {$url = $_server [' Reques T_uri '];} else {$url = $_SERVER [' php_self ']; $url. = Empty ($_server [' query_string '])? ‘‘ : ‘?‘ . $_server [' query_string '];} return $url;} /** * Output error message */private function error ($STR) {echo ' <div style= ' color:red; ' > '. $str. ' </div> ';}}

  

How to use:

Here's how to use it:

Part of the code is placed before the logical code to be cached:

$cachedir = './cache/'; Set cache Directory $cache = new cache ($cachedir, 33); The default setting for omitting parameters is $cache = new cache ($CACHEDIR); if (@$_get [' cacheact ']! = ' rewrite ' | | @$_get [' clearcache '] = = ' OK ')//Here is a trick, through XX. Php?cacheact=rewrite update the cache, and so on, you can also set some other operations $cache->load (); Load cache, cache is valid do not execute the following page code//page code start

  

Part is placed behind the cached logic code:

Page code end $cache->write (); First run or cache expiration, generating cache

  

Original address: Http://sijienet.com/bbs/?leibie=showinfo&id=50

PHP Cache Tool class implements Web caching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.