PHP method to implement web page compression function based on ob_start(ob_gzhandler)

高洛峰
Release: 2023-03-05 21:10:01
Original
1743 people have browsed it

This article mainly introduces how PHP implements web page compression function based on ob_start('ob_gzhandler'), involving ob_gzip, ob_start and other functions in PHP to operate the buffer and content compression related techniques. Friends in need can refer to the following

The example in this article describes how PHP implements web page compression function based on ob_start('ob_gzhandler'). Share it with everyone for your reference, the details are as follows:

PHP generates a web page and sends it to the browser for display. In addition to the user's Internet speed, the opening speed of the page is often closely related to the size of the page. We can Start with web page size to improve web page responsiveness.

The following code is an example of compressing a web page. We use the ob_gzip function and ob_start to compress the output content and put it into the "buffer" before outputting it.

PHP code

//启用压缩
if(function_exists('ob_gzip'))
{
 ob_start('ob_gzip');
}
//准备一些待压缩的内容
for($i=0; $i<100; $i++)
{
 echo(&#39;这里是测试内容 <br>&#39;);
}
//输出压缩成果
ob_end_flush();
//这是ob_gzip压缩函数
function ob_gzip ($content)
{
 if( !headers_sent() && extension_loaded ("zlib") && strstr ( $_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")){
 $content = gzencode($content,9);
 header ("Content- Encoding: gzip");
 header ("Vary: Accept- Encoding");
 header ("Content- Length: ".strlen ($content));
 }
 return ($content) ;
}
Copy after login

How effective is it? Here I tested the above code.

Before compression:

PHP method to implement web page compression function based on ob_start(ob_gzhandler)

After compression:

PHP method to implement web page compression function based on ob_start(ob_gzhandler)

More php based on ob_start(ob_gzhandler) For related articles on how to implement web page compression function, please pay attention to 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!