PHP zlib扩展实现页面GZIP压缩输出
要实现GZIP压缩页面需要浏览器和服务器共同支持,实际上就是服务器压缩,传到浏览器后浏览器解压并解析。浏览器那边不需要我们担心,因为现在绝大多数浏览器都支持解析GZIP过的页面。我们只要把页面在服务器端压缩再输出到浏览器就行了。
有点罗嗦,下面说正事:
正如要制作压缩饼干,先要拿到原料,要压缩一个页面,首先要获得要输出的内容。PHP中的ob_start()(ob => output buffer)函数可以实现这个功能,它可以把程序里准备输出的内容先放到一个叫做“缓冲区”的地方,当然,你可以理解为制作压缩饼干的暂时放原料的工作台。
这个函数一定要在页面输出之前使用,所以一般把它放在代码的最顶端。因为它就像是一个工作台,所以你要在原料到来之前就要准备好它,否则原料来了没地方放,会出问题的。用ob_start()得到要压缩的页面之后,我们就可以制作压缩饼干了,不对,应该是可以压缩页面了!不过好像还缺少一台压缩机, EZ,我们用PHP带的zlib扩展做一台:
复制代码 代码如下:
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()变成
ob_start('ob_gzip'); //没错,就是给ob_start()加一个参数,参数名就是我们刚才做的“压缩机”的函数名。这样当内容进入缓冲区后PHP就会调用ob_gzip函数把它压缩了。
好了,所有的工作已完成,最后交货:
ob_end_flush(); //结束缓冲区,输出内容。当然,不用这个函数也行,因为程序执行到最后会自动将缓冲区内容输出。
完整的示例如下:
复制代码 代码如下:
//启用一个带有ob_gzip压缩机的工作台
ob_start('ob_gzip');
//准备一些待压缩的内容
for($i=0; $i{
echo('这里是压缩饼干的原料,这里是压缩饼干的原料,原料');
}
//输出压缩成果
ob_end_flush();
//这是ob_gzip压缩机
function ob_gzip($content)
{
if( !headers_sent() &&
extension_loaded("zlib") &&
strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip"))
{
$content = gzencode($content." \n//此页已压缩",9);
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
header("Content-Length: ".strlen($content));
}
return $content;
}
?>
经过实际测试,上面代码中如果不用GZIP,是4.69KB=4802.56B,启用GZIP后缩小为104B ,呃……我数学可能不好,自己算下压缩到了原来的百分之多少吧。。
另外,下面是用FlashGet获取的日志信息,可以看到我们程序里加的header信息:
复制代码 代码如下:
Fri Jan 25 17:53:10 2008 HTTP/1.1 200 OK
Fri Jan 25 17:53:10 2008 Server: Microsoft-IIS/5.1
Fri Jan 25 17:53:10 2008 Date: Fri, 25 Jan 2008 09:53:10 GMT
Fri Jan 25 17:53:10 2008 Connection: close
Fri Jan 25 17:53:10 2008 X-Powered-By: PHP/5.2.5
Fri Jan 25 17:53:10 2008 Content-Encoding: gzip
Fri Jan 25 17:53:10 2008 Vary: Accept-Encoding
Fri Jan 25 17:53:10 2008 Content-Length: 104
Fri Jan 25 17:53:10 2008 Content-type: text/html

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

As the world's leading digital asset trading platform, Ouyi OKX attracts many investors with its rich trading products, strong security guarantees and convenient user experience. However, the risks of network security are becoming increasingly severe, and how to safely register the official Ouyi OKX account is crucial. This article will provide the latest registration portal for Ouyi OKX official website, and explain in detail the steps and precautions for safe registration, including how to identify the official website, set a strong password, enable two-factor verification, etc., to help you start your digital asset investment journey safely and conveniently. Please note that there are risks in digital asset investment, please make cautious decisions.

Coinbase Security Login Guide: How to Avoid Phishing Sites and Scams? Phishing and scams are becoming increasingly rampant, and it is crucial to securely access the Coinbase official login portal. This article provides practical guides to help users securely find and use the latest official login portal of Coinbase to protect the security of digital assets. We will cover how to identify phishing sites, and how to log in securely through official websites, mobile apps or trusted third-party platforms, and provide suggestions for enhancing account security, such as using a strong password and enabling two-factor verification. To avoid asset losses due to incorrect login, be sure to read this article carefully!

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

This article details how to register an account on the official website of Ouyi OKX Exchange and start cryptocurrency trading. As the world's leading cryptocurrency exchange, Ouyi provides a wide range of trading varieties, multiple trading methods and strong security guarantees, and supports convenient withdrawal of a variety of fiat and cryptocurrencies. The article covers the search methods for Ouyi official website registration entrance, detailed registration steps (including email/mobile registration, information filling, verification code verification, etc.), as well as precautions after registration (KYC certification, security settings, etc.), and answers common questions to help novice users quickly and safely complete Ouyi account registration and start a cryptocurrency investment journey.

This article provides Android and Apple mobile APP download methods for mainstream digital currency trading platforms such as Binance, OKX, Gate.io, Huobi Global, Coinbase, KuCoin, Kraken and Bitfinex. Whether it is an Android user or an Apple user, you can easily find the official APP download link for the corresponding platform and complete the installation according to the steps. The article provides detailed guidance on searching and downloading on their respective official websites or app stores, and provides instructions on the special steps for installing APK files on Android, so that users can download and use them quickly and easily.

Binance official website real-name authentication tutorial: Improve account security, unlock more transaction functions and higher amounts! This article guides you in detail to complete Binance account authentication, including logging in to the official website, entering the verification page, selecting the authentication level (basic, intermediate, and advanced, covering uploading of ID cards, passports and other documents and video verification), and viewing review results. Quickly complete Binance real-name authentication to ensure the safety of your account and enjoy a more convenient transaction experience!

LOOM Coin, a once-highly-known blockchain game and social application development platform token, its ICO was held on April 25, 2018, with an issue price of approximately US$0.076 per coin. This article will conduct in-depth discussion on the issuance time, price and important precautions of LOOM coins, including market volatility risks and project development prospects. Investors should be cautious and do not follow the trend blindly. It is recommended to refer to the official website of Loom Network, blockchain browser and cryptocurrency information platform to obtain the latest information and conduct sufficient risk assessment. The information in this article is for reference only and does not constitute investment advice. Learn about LOOM coins, start here!

This article provides a safe and reliable Binance Exchange App download guide to help users solve the problem of downloading Binance App in the country. Due to restrictions on domestic application stores, the article recommends priority to downloading APK installation packages from Binance official website, and introduces three methods: official website download, third-party application store download, and friends sharing. At the same time, it emphasizes security precautions during the download process, such as verifying the official website address, checking application permissions, scanning with security software, etc. In addition, the article also reminds users to understand local laws and regulations, pay attention to network security, protect personal information, beware of fraud, rational investment, and secure transactions. At the end of the article, the article once again emphasized that downloading and using Binance App must comply with local laws and regulations, and at your own risk, and does not constitute any investment advice.
