Home Backend Development PHP Tutorial Another cache class

Another cache class

Jul 25, 2016 am 09:11 AM

Cache class
  1. /*
  2. * Cache class cache
  3. * Author: Duo Noob
  4. * Creation time: 2006-05-05
  5. * Example:
  6. include( "cache.php" );
  7. $cache = new cache(30);
  8. $cache->cacheCheck();
  9. echo date("Y-m-d H:i:s");
  10. $cache->caching();
  11. */
  12. class cache {
  13. // Cache directory
  14. var $cacheRoot = "./cache/";
  15. //Cache update time in seconds, 0 means no caching
  16. var $cacheLimitTime = 0;
  17. //Cache file name
  18. var $cacheFileName = "";
  19. / /Cache extension
  20. var $cacheFileExt = "php";
  21. /*
  22. * constructor
  23. * int $cacheLimitTime cache update time
  24. */
  25. function cache( $cacheLimitTime ) {
  26. if( intval( $cacheLimitTime ) )
  27. $ this->cacheLimitTime = $cacheLimitTime;
  28. $this->cacheFileName = $this->getCacheFileName();
  29. ob_start();
  30. }
  31. /*
  32. * Check whether the cache file is within the set update time
  33. * Return: If it is within the update time, return the file content, otherwise it will return failure
  34. */
  35. function cacheCheck(){
  36. if( file_exists( $this->cacheFileName ) ) {
  37. $cTime = $this->getFileCreateTime ( $this->cacheFileName );
  38. if( $cTime + $this->cacheLimitTime > time() ) {
  39. echo file_get_contents( $this->cacheFileName );
  40. ob_end_flush();
  41. exit;
  42. }
  43. }
  44. return false;
  45. }
  46. /*
  47. * Cache files or output static
  48. * string $staticFileName static file name (including relative path)
  49. */
  50. function caching( $staticFileName = "" ){
  51. if( $this ->cacheFileName ) {
  52. $cacheContent = ob_get_contents();
  53. //echo $cacheContent;
  54. ob_end_flush();
  55. if( $staticFileName ) {
  56. $this->saveFile( $staticFileName, $cacheContent );
  57. }
  58. if( $this->cacheLimitTime )
  59. $this->saveFile( $this->cacheFileName, $cacheContent );
  60. }
  61. }
  62. /*
  63. * Clear cache files
  64. * string $fileName specified file name (including functions) or all (all)
  65. * Return: true if clearing is successful, otherwise false
  66. */
  67. function clearCache( $fileName = "all" ) {
  68. if( $fileName != "all" ) {
  69. $fileName = $this->cacheRoot . strtoupper(md5($fileName)).".".$this->cacheFileExt;
  70. if( file_exists( $fileName ) ) {
  71. return @unlink( $fileName );
  72. }else return false;
  73. }
  74. if ( is_dir( $this->cacheRoot ) ) {
  75. if ( $dir = @opendir( $this->cacheRoot ) ) {
  76. while ( $file = @readdir( $dir ) ) {
  77. $check = is_dir( $file );
  78. if ( !$check )
  79. @unlink( $this->cacheRoot . $file );
  80. }
  81. @closedir( $dir );
  82. return true;
  83. }else{
  84. return false;
  85. }
  86. }else{
  87. return false;
  88. }
  89. }
  90. /*
  91. * Generate a cache file name based on the current dynamic file
  92. */
  93. function getCacheFileName() {
  94. return $this-> cacheRoot . strtoupper(md5($_SERVER["REQUEST_URI"])).".".$this->cacheFileExt;
  95. }
  96. /*
  97. * Cache file creation time
  98. * string $fileName cache file name (including relative path) )
  99. * Return: file generation time in seconds, if the file does not exist, return 0
  100. */
  101. function getFileCreateTime( $fileName ) {
  102. if( ! trim($fileName) ) return 0;
  103. if( file_exists( $fileName ) ) {
  104. return intval(filemtime( $fileName ));
  105. }else return 0;
  106. }
  107. /*
  108. * Save the file
  109. * string $fileName file name (including relative path)
  110. * string $text file content
  111. * Return: Returns true on success, false on failure
  112. */
  113. function saveFile($fileName, $text) {
  114. if( ! $fileName || ! $text ) return false;
  115. if( $this->makeDir( dirname( $ fileName ) ) ) {
  116. if( $fp = fopen( $fileName, "w" ) ) {
  117. if( @fwrite( $fp, $text ) ) {
  118. fclose($fp);
  119. return true;
  120. }else {
  121. fclose($fp);
  122. return false;
  123. }
  124. }
  125. }
  126. return false;
  127. }
  128. /*
  129. * Continuously create directories
  130. * string $dir directory string
  131. * int $mode permission number
  132. * return : Return true if created successfully or all have been built, otherwise return false
  133. */
  134. function makeDir( $dir, $mode = "0777" ) {
  135. if( ! $dir ) return 0;
  136. $dir = str_replace( "\ ", "/", $dir );
  137. $mdir = "";
  138. foreach( explode( "/", $dir ) as $val ) {
  139. $mdir .= $val."/";
  140. if( $val == ".." || $val == "." || trim( $val ) == "" ) continue;
  141. if( ! file_exists( $mdir ) ) {
  142. if(!@mkdir( $mdir, $mode )){
  143. return false;
  144. }
  145. }
  146. }
  147. return true;
  148. }
  149. }
  150. ?>
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

See all articles