Home  >  Article  >  Backend Development  >  PHP实现gzip页面压缩的方法

PHP实现gzip页面压缩的方法

WBOY
WBOYOriginal
2016-06-20 13:03:471234browse

PHP两种方法实现gzip页面压缩,不过这两种方法实现的前提是服务器要支持gzip压缩才行,服务器不支持的话,两种方法都是白搭了。

下面正文开始介绍如何利用 php 实现 gzip 页面压缩功能。

方法一(用php的内置压缩函数):

<p><?PHP </p>if(Extension_Loaded('zlib')) Ob_Start('ob_gzhandler'); <br />Header("Content-type: text/html"); <br />?> <br /><html> <br /><head> <br /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <br /><title>scutephp</title> <br /></head> <br /><body> <br /><?php <br />for($i=0;$i<10000;$i++){ <br />echo 'Hello World!'; <br />} <br />?> <br /></body> <br /></html> <br /><?PHP <br />if(Extension_Loaded('zlib')) Ob_End_Flush(); <br /><p>?>

方法二(自写函数):

<p><?php ob_start('ob_gzip'); ?> </p><html> <br /><head> <br /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <br /><title>scutephp</title> <br /></head> <br /><body> <br /></body> <br /></html> <br /><?php <br />ob_end_flush(); <br />//压缩函数 <br />function ob_gzip($content){ <br />if(!headers_sent()&&extension_loaded("zlib")&&strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")){ <br />$content = gzencode($content,9); <br />header("Content-Encoding: gzip"); <br />header("Vary: Accept-Encoding"); <br />header("Content-Length: ".strlen($content)); <br />} <br />return $content; <br />} <br />?>


Statement:
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