Home Backend Development PHP Tutorial php enables gzip compression to accelerate website

php enables gzip compression to accelerate website

Jul 25, 2016 am 08:45 AM

php, gzip


Description:

The compressed files are cached on the server, which reduces re-compression time and CPU usage when accessed again. By setting the client file cache time and reducing the number of re-requests, it can be reduced by more than 85%. Because the image is already in a compressed format, only the client cache time is set and no compression is performed.

How to use:

The server must support gzip and Rewrite functions. Add the following code RewriteRule (..css$|..js$|..jpg$|..gif$|.*.png$) gzip.php in the line below "RewriteBase /" in the .htacess file ?$1 Upload gzip.php to the root directory

4. Create a cache folder in the root directory to ensure it is readable and writable.

  1. /**
  2. * @author Seraphim
  3. * @copyright 2012
  4. */
  5. //
  6. function sendheader($last_modified, $p_type, $content_length = 0 )
  7. {
  8. //Set the client cache validity time
  9. header("Expires: " . gmdate("D, d M Y H:i:s", time() + 15360000) . "GMT");
  10. header("Cache -Control: max-age=315360000");
  11. header("Pragma: ");
  12. // Set the last modification time
  13. header("Last-Modified: " . $last_modified);
  14. // Set the file type information
  15. header ($p_type);
  16. header("Content-Length: " . $content_length);
  17. }
  18. define('ABSPATH', dirname(__file__) . '/');
  19. $cache = true;
  20. $cachedir = 'cache /'; //The directory where gz files are stored must be writable
  21. if (empty($_SERVER['QUERY_STRING']))
  22. exit();
  23. $gzip = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' );
  24. if (empty($gzip))
  25. $cache = false;
  26. $key = array_shift(explode('?', $_SERVER['QUERY_STRING']));
  27. $key = str_replace('../' , '', $key);
  28. $filename = ABSPATH . $key;
  29. $symbol = '_';
  30. $rel_path = str_replace(ABSPATH, '', dirname($filename));
  31. $namespace = str_replace(' /', $symbol, $rel_path);
  32. $cache_filename = ABSPATH . $cachedir . $namespace . $symbol . basename($filename) .
  33. '.gz'; //Generate gz file path
  34. $ext = array_pop(explode ('.', $filename)); //Judge file type information based on suffix
  35. $type = "Content-type: text/html"; //Default file type
  36. switch ($ext)
  37. {
  38. case 'css ':
  39. $type = "Content-type: text/css";
  40. break;
  41. case 'js':
  42. $type = "Content-type: text/javascript";
  43. break;
  44. case 'gif':
  45. $ cache = false;
  46. $type = "Content-type: image/gif";
  47. break;
  48. case 'jpg':
  49. $cache = false;
  50. $type = "Content-type: image/jpeg";
  51. break;
  52. case 'png':
  53. $cache = false;
  54. $type = "Content-type: image/png";
  55. break;
  56. default:
  57. exit();
  58. }
  59. if ($cache)
  60. {
  61. if ( file_exists($cache_filename))
  62. { // If a gz file exists
  63. $mtime = filemtime($cache_filename);
  64. $gmt_mtime = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
  65. if ((isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && array_shift(explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE'])) ==
  66. $gmt_mtime))
  67. {
  68. // with files in browser cache The modification date is consistent and 304 is returned. header("HTTP/1.1 304 Not Modified");
  69. // Send client header
  70. header("Content-Encoding:gzip");
  71. sendheader($gmt_mtime, $type);
  72. }
  73. else
  74. {
  75. // Read gz file output
  76. $content = file_get_contents($cache_filename);
  77. // Send client header
  78. sendheader($gmt_mtime, $type, strlen($content));
  79. header("Content -Encoding: gzip");
  80. // Send data
  81. echo $content;
  82. }
  83. }
  84. else
  85. if (file_exists($filename))
  86. { // There is no corresponding gz file
  87. $mtime = mktime();
  88. $gmt_mtime = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
  89. // Read the file
  90. $content = file_get_contents($filename);
  91. // Remove the blank part
  92. // $content = ltrim($content);
  93. // Compress file content
  94. $content = gzencode($content, 9, $gzip ? FORCE_GZIP : FORCE_DEFLATE);
  95. // Send client header
  96. sendheader($gmt_mtime, $type, strlen($content));
  97. header("Content-Encoding: gzip");
  98. // Send data
  99. echo $content;
  100. // Write file
  101. file_put_contents($cache_filename, $content);
  102. }
  103. else
  104. {
  105. header("HTTP/1.0 404 Not Found");
  106. }
  107. }
  108. else
  109. { // Process output in Gzip mode. The principle is basically the same as above
  110. if (file_exists($filename))
  111. {
  112. $mtime = filemtime($filename);
  113. $gmt_mtime = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
  114. if ((isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && array_shift(explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE'])) ==
  115. $gmt_mtime))
  116. {
  117. // with files in browser cache The modification date is consistent and 304 is returned. header("HTTP/1.1 304 Not Modified");
  118. // Send client header
  119. sendheader($gmt_mtime, $type, strlen($content));
  120. header("Content-Encoding: gzip");
  121. }
  122. else
  123. {
  124. // Read file output
  125. $content = file_get_contents($filename);
  126. // Send client header
  127. sendheader($gmt_mtime, $type, strlen($content));
  128. // Send data
  129. echo $content;
  130. }
  131. }
  132. else
  133. {
  134. header("HTTP/1.0 404 Not Found");
  135. }
  136. }
  137. ?>
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,

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 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...

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...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

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�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles