zlib,gzip和deflate格式分析之php相互转换
LZ77: 是一种基于字典的无损数据压缩算法(还有 LZ78, LZW 等)
deflate: 也是一种数据压缩算法,实际上就是先用 LZ77 压缩,然后用霍夫曼编码压缩
gzip: 是一种文件结构,也可以算一种压缩格式,通过 defalte 算法压缩数据,然后加上文件头和adler32校验
zlib: 是一个提供了 deflate, zlib, gzip 压缩方法的函数库;也是一种压缩格式(用 deflate 压缩数据,然后加上 zlib 头和 CRC 校验)
1 <?php 2 3 $string = "11aa@#@23123szadler32adler32adler32f..adler32adler32"; 4 $level = 9; 5 6 echo "字符串长度:"; 7 echo strlen($string); 8 9 echo "\r\n-------------------------------\r\ngzcompress压缩后长度:"; 10 $zlib = gzcompress($string, $level); 11 echo strlen($zlib); 12 file_put_contents('zlib.txt', $zlib); 13 14 $src_zlib = substr($zlib, 2, -4); 15 echo "\r\nzlib还原: " . gzinflate($src_zlib); 16 17 $zlib_header = pack("H*", '78DA'); 18 /* 19 0,1 01 20 2,3,4 5e 21 -1,6 9c 22 7+ da 23 */ 24 echo "\r\nzlib-header(2位): " . bin2hex($zlib_header); 25 echo "\r\nADLER32校验傎: "; 26 $adler32 = hash('adler32', $string); 27 $zlib_adler32 = pack("H*", $adler32); 28 echo $adler32; 29 30 echo "\r\n-------------------------------\r\ngzencode压缩后长度:"; 31 $gzip = gzencode($string, $level); 32 echo strlen($gzip); 33 file_put_contents('gzip.txt', $gzip); 34 35 $src_gzip = substr($gzip, 10, -8); 36 echo "\r\ngzip还原: " . gzinflate($src_gzip); 37 $gzip_header = pack("H*", '1F8B0800000000000003'); 38 echo "\r\ngzip-header(20位): " . bin2hex($gzip_header); 39 40 function revx_split($str){ 41 return implode('', array_reverse(str_split(sprintf("%08X", $str), 2))); 42 } 43 44 $crc32 = revx_split(crc32($string)); 45 $gzip_crc32 = pack("H*", $crc32); 46 $length = revx_split(strlen($string)); 47 $gzip_length = pack("H*", $length); 48 echo "\r\ngzip-crc32: {$crc32}"; 49 echo "\r\ngzip-Length: {$length}"; 50 51 echo "\r\n-------------------------------\r\ngzdeflate压缩后长度:"; 52 $deflate = gzdeflate($string, $level); 53 echo strlen($deflate); 54 file_put_contents('deflate.txt', $deflate); 55 56 echo "\r\n-------------------------------\r\n用gzdecode解压gzdeflate:"; 57 echo file_put_contents('gzdecode.gz', $gzip_header . $deflate . $gzip_crc32 . $gzip_length); 58 59 echo "\r\n-------------------------------\r\n用gzuncompress解压gzdeflate:"; 60 echo gzuncompress($zlib_header . $deflate . $zlib_adler32);