Home >Backend Development >PHP Tutorial >Two examples of php gzip page compression

Two examples of php gzip page compression

WBOY
WBOYOriginal
2016-07-25 08:59:481056browse
Let me give you two examples of PHP using gzip for page compression. Gzip can compress js, css, image files, etc. The two simple examples introduced in this article are especially suitable for reference by beginners. Come and take a look.

Example 1, example of PHP built-in compression function

<?PHP 
/**
 * php 内置函数压缩
* bbs.it-home.org
*/
if(Extension_Loaded('zlib')) Ob_Start('ob_gzhandler'); 
Header("Content-type: text/html"); 
?> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>php程序员的笔记</title> 
</head> 
<body> 
<?php 
for($i=0;$i<10000;$i++){ 
echo 'Hello World!'; 
} 
?> 
</body> 
</html> 
<?PHP 
if(Extension_Loaded('zlib')) Ob_End_Flush(); 
?>

Example 2, self-written function to achieve compression

<?php ob_start('ob_gzip'); ?> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>自写函数压缩_bbs.it-home.org</title> 
</head> 
<body> 
</body> 
</html> 
<?php 
ob_end_flush(); 
//压缩函数 
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; 
} 
?>


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