How to enable gzip in PHP to improve web page response speed

小云云
Release: 2023-03-20 22:12:02
Original
3249 people have browsed it

This article mainly shares with you how to enable gzip in PHP to improve web page response speed. I hope it can help everyone.

1. Turn on gzip in apache (this method requires restarting the server):

a. Turn on the module:

LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
Copy after login

b.Add in httpd.conf

<ifmodule deflate_module>  DeflateCompressionLevel 9  
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/json application/xml
  AddOutputFilter DEFLATE js css
  AddOutputFilter INCLUDES .shtml .htm .xml .php .html</ifmodule>
Copy after login

c. Restart the server

2. PHP enables gzip

Principle:

header("Content-Encoding: gzip");echo gzencode(&#39;songjiankang&#39;);
Copy after login

Example 1:

function ob_gzip ($content) // $content 就是要压缩的页面内容,或者说饼干原料{    if (! headers_sent() &&     // 如果页面头部信息还没有输出
    extension_loaded("zlib") &&     // 而且zlib扩展已经加载到PHP中
    strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip"))     // 而且浏览器说它可以接受GZIP的页面    {        $content = gzencode($content . " \n//此页已压缩", 9); // 此页已压缩”的注释标签,然后用zlib提供的gzencode()函数执行级别为9的压缩,这个参数值范围是0-9,0表示无压缩,9表示最大压缩,当然压缩程度越高越费CPU。
                                                                  
        // 然后用header()函数给浏览器发送一些头部信息,告诉浏览器这个页面已经用GZIP压缩过了!
        header("Content-Encoding: gzip");        header("Vary: Accept-Encoding");        header("Content-Length: " . strlen($content));
    }    return $content; // 返回压缩的内容,或者说把压缩好的饼干送回工作台。}ob_start(&#39;ob_gzip&#39;);
Copy after login

Example 2:

#ob_gzhandler 为php内置函数,具体参考手册ob_start(&#39;ob_gzhandler&#39;);
Copy after login

Related recommendations:

How to enable GZIP compression in Apache

php determines whether the page file has been gzip compressed

Teach you how to enable Gzip compression method in Node.js

The above is the detailed content of How to enable gzip in PHP to improve web page response speed. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!