PHP: zlib圧縮関数 - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<zip_readgzclose>
view the version of this page
Last updated: Tue, 21 Dec 2004

CXXXV. zlib圧縮関数

導入

このモジュールによりgzip (.gz)で圧縮されたファイルを読み書きする ことが可能となります。 この際、ファイルシステム関 数のgzip圧縮対応版(非圧縮ファイルも扱えますが、ソケットは扱えませ ん)を使用します。

注意: バージョン4.0.4-devで.gzファイルに対応したfopen-wrapperを導入しました。 これによりfopen()に'zlib:'をプレフィクスとした ファイル名又はパス名を渡すことで、通常のf*()関数で圧縮されたファイルに 透過的にアクセスすることが出来ます。

4.3.0において、';'を含むファイル名との曖昧さを避けるためこの特別 なプレフィックスは'zlib://'に変更されました。

この機能を利用するにはfopencookie()関数を提供する Cのランタイムライブラリが必要です。現在私の知る限りでは、GNU libcが この機能を提供する唯一のライブラリです。

要件

このモジュールは、Jean-loup Gailly および Mark Adler による の関数を使用します。 このモジュールを使用するには、zlib バージョン 1.0.9 以上を 使用する必要があります。

インストール手順

PHPにおけるZlibサポートは、デフォルトでは利用できません。 Zlibサポートを有効にするには、PHPのコンパイル時にconfigureの オプションに--with-zlib[=DIR]を 指定してコンパイルする必要があります。

Windows版のPHPには この拡張モジュールのサポートが組み込まれています。これらの関数を使用 するために拡張モジュールを追加でロードする必要はありません。

注意: PHP 4.3.0 以降、zlib モジュールは php バイナリにビルトインされています。

実行用の設定

これらの関数の動作は、php.iniの設定により変化します。

zlib拡張モジュールは、ブラウザがサポートする場合にページを透過的に圧 縮するオプションを提供します。 ここで、 設定ファイル php.ini のオプションには、以下の3種類があります。

表 1. Zlib設定オプション

名前デフォルト変更の可否
zlib.output_compression"Off"PHP_INI_ALL
zlib.output_compression_level"-1"PHP_INI_ALL
zlib.output_handler""PHP_INI_ALL
PHP_INI_*定数の定義と詳細については、 ini_set()を参照して下さい。

以下に設定ディレクティブに関する簡単な説明を示します。

zlib.output_compression boolean/integer

透過的なページ圧縮を行うかどうか。php.iniまたはApacheの設定で このオプションが、"On"に設定された場合、 ブラウザが"Accept-Encoding: gzip"または"deflate"ヘッダを送信する 場合に、ページは圧縮されます。 "Content-Encoding: gzip" (および"deflate")と"Vary: Accept-Encoding"ヘッダが出力に追加されます。

ヘッダが未送信の場合、スクリプト内でこのオプションを無効にするた めにini_set()を使用することが可能です。 "Content-Type: image/"ヘッダを出力した場合、(Netscapeのバグのせ いで)圧縮が無効となります。 image content-typeを追加するヘッダコールの後、 "ini_set('zlib.output_compression', 'On')"を追加した場合、 再度有効にすることができます。

このオプションも論理値"On"/"Off"のかわりに整数値をとることができ、 これを用いて出力のバッファサイズ(デフォルトは4KB)を設定すること ができます。

注意: このオプションに'On'を設定した場合、 output_handlerを空に する必要があります! かわりにzlib.output_handlerを使用する必要が あります。

zlib.output_compression_level integer

透過的出力圧縮で使用される圧縮レベル。

zlib.output_handler string

zlib.output_compressionが有効な場合に他の出力ハンドラを指定する ことはできません。この設定は、 output_handlerと同じですが、順番が異なります。

簡単なコードの例

テンポラリファイルをオープンし、テスト用文字列を書きこみ、 続いて、このファイルの内容を2回出力します。

例 1. 簡単な Zlib の例

<?php
$filename
= tempnam ('/tmp', 'zlibtest').'.gz';
print
"<html>\n<head></head>\n<body>\n<pre>\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";
// 最大限の圧縮を指定して書きこみ用にファイルをオープン
$zp = gzopen ($filename, "w9");
// 文字列をファイルに書きこむ
gzwrite ($zp, $s);
// ファイルを閉じる
gzclose ($zp);
// 読みこみ用にファイルをオープン
$zp = gzopen ($filename, "r");
// 3文字読みこむ
print gzread ($zp, 3);
// ファイルの終端まで読み、閉じる
gzpassthru ($zp);
print
"\n";
// ファイルをオープンし、内容を出力する (2回目)。
if (readgzfile ($filename) != strlen ($s)) {
       echo
"Error with zlib functions!";
}
unlink ($filename);
print
"</pre>\n</h1></body>\n</html>\n";
?>
目次
gzclose -- 開かれたgzファイルへのポインタを閉じる
gzcompress -- 文字列をdeflate圧縮する
gzdeflate -- 文字列を deflate 圧縮する
gzencode -- gzip 圧縮された文字列を作成
gzeof -- gz ファイルポインタにおいてファイル終端を調べる
gzfile -- gzファイル全体を配列に読み込む
gzgetc -- gz ファイルへのポインタから文字を得る
gzgets -- ファイルポインタから 1 行を得る
gzgetss --  gzファイルへのポインタから1行を得て、HTMLタグを取り除く
gzinflate -- deflate圧縮された文字列を解凍する
gzopen -- gz ファイルを開く
gzpassthru --  gzファイルへのポインタから残りのデータ全部を出力する
gzputs -- gz ファイルへのポインタに書き込む
gzread -- バイナリ対応のgzファイル読み込み
gzrewind -- gz ファイルポインタの示す位置を元に戻す
gzseek -- gz ファイルポインタの位置を移動する
gztell -- gzファイルポインタの読み込み/書き込み位置を返します
gzuncompress -- deflate圧縮された文字列を解凍する
gzwrite -- バイナリ対応のgzファイル書き込み
readgzfile -- gz ファイルを出力する
zlib_get_coding_type -- Returns the coding type used for output compression


add a note add a note User Contributed Notes
zlib圧縮関数
admin_at_commandline_dot_ch
08-Oct-2004 12:32
My gzip function.

This function read, compress and writhe only small chunks at one time, this way you can compress big files without memory problems...

<?php
function gzip($src, $level = 5, $dst = false){
   if(
$dst == false){
      
$dst = $src.".gz";
   }
   if(
file_exists($src)){
      
$filesize = filesize($src);
      
$src_handle = fopen($src, "r");
       if(!
file_exists($dst)){
          
$dst_handle = gzopen($dst, "w$level");
           while(!
feof($src_handle)){
              
$chunk = fread($src_handle, 2048);
              
gzwrite($dst_handle, $chunk);
           }
          
fclose($src_handle);
          
gzclose($dst_handle);
           return
true;
       } else {
          
error_log("$dst already exists");
       }
   } else {
      
error_log("$src doesn't exist");
   }
   return
false;
}
?>
gem at rellim dot com
14-Jul-2004 03:03
Run, do not walk, run, to add this to your Apache config file:

php_flag zlib.output_compression On
php_value zlib.output_compression_level 5

I just tried this and achieved 10x and 15x speed inprovement on
some mature php pages.  Pages I have been seating over to make 5% gains on.  I use microtime() on critical pages to help me track page speed and that confirms the speed improvement.  The php page takes a timestamp at the beginning and end, then logs the page duration.  So any IP transmission effects are not included.  There is
a clear subjective difference to the user.

The test system was PHP 4.3.6, Apache 2.0.49 over Linux 2.4.
As always YMMV.
zigazou at free dot fr
12-Jun-2004 10:44
If you use "zlib.output_compression = On" in your php.ini file, and activates output buffering (ob_start), don't output this header :
header('Content-Length: '.ob_get_length());

This is because ob_get_length() will return the uncompressed size while zlib will compress the output. Thus your browser will get confused waiting for extra data that will never come.
xorinox at tiscali dot ch
04-Jun-2004 02:52
Have a look to this extended version :)

<?php

function compress( $srcFileName, $dstFileName )
{
  
// getting file content
  
$fp = fopen( $srcFileName, "r" );
  
$data = fread ( $fp, filesize( $srcFileName ) );
  
fclose( $fp );
  
  
// writing compressed file
  
$zp = gzopen( $dstFileName, "w9" );
  
gzwrite( $zp, $data );
  
gzclose( $zp );
}

function
uncompress( $srcFileName, $dstFileName, $fileSize )
{
  
// getting content of the compressed file
  
$zp = gzopen( $srcFileName, "r" );
  
$data = fread ( $zp, $fileSize );
  
gzclose( $zp );
  
  
// writing uncompressed file
  
$fp = fopen( $dstFileName, "w" );
  
fwrite( $fp, $data );
  
fclose( $fp );
}

compress( "tmp/supportkonzept.rtf", "tmp/_supportkonzept.rtf.gz" );
uncompress( "tmp/_supportkonzept.rtf.gz", "tmp/_supportkonzept.rtf", filesize( "tmp/supportkonzept.rtf" ) );

?>
ec10 at gmx dot net
20-May-2004 06:38
/**
 * @return bool
 * @param string $in
 * @param string $out
 * @param string $param = "1"
 * @desc compressing the file with the zlib-extension
*/
function gzip ($in, $out, $param="1")
{
   if (!file_exists ($in) || !is_readable ($in))
       return false;
   if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
       return false;
  
   $in_file = fopen ($in, "rb");
   if (!$out_file = gzopen ($out, "wb".$param)) {
       return false;
   }
  
   while (!feof ($in_file)) {
       $buffer = fgets ($in_file, 4096);
       gzwrite ($out_file, $buffer, 4096);
   }

   fclose ($in_file);
   gzclose ($out_file);
  
   return true;
}

/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc uncompressing the file with the zlib-extension
*/
function gunzip ($in, $out)
{
   if (!file_exists ($in) || !is_readable ($in))
       return false;
   if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
       return false;

   $in_file = gzopen ($in, "rb");
   $out_file = fopen ($out, "wb");

   while (!gzeof ($in_file)) {
       $buffer = gzread ($in_file, 4096);
       fwrite ($out_file, $buffer, 4096);
   }
 
   gzclose ($in_file);
   fclose ($out_file);
  
   return true;
}
spam at wildpeaks dot com
14-May-2004 02:04
For decompressing, i modified a function posted earlier (that way $string doesn't have a big size that may be beyond the memory limit if the gzipped file is big) :

function file_ungzip($fromFile, $toFile) {
   $zp = @gzopen($fromFile, "r");
   $fp = @fopen($toFile, "w");
   while(!@gzeof($zp)) {$string = @gzread($zp, 4096); @fwrite($fp, $string, strlen($string));}
   @gzclose($zp);
   @fclose($fp);
}
thivierr at telus dot net
17-Nov-2003 12:02
I found the absolute easiest way to read a gzip file is as follows:

echo file_get_contents("compress.zlib:///myphp/test.txt.gz");

To create a gzip file:
file_put_contents("compress.zlib:///myphp/test.txt.gz","Put this in the file\r\n");

Things to note about this:
-The best prefix to use is "compress.zlib", not "zlib"
-If you wish to specify a path starting in the root path, you actually end up with three slashes.  The above path corresponds to "/myphp/test.txt" on unix, and "c:\myphp\test.txt" on Windows (if C: is the current drive).  I tested it just on Windows.
-Compression and decompression both use the same prefix of "compress.zlib://" (plus one more slash to get a root dir).
-I'm using 5.0, so I'm not 100% sure which behaviour started in which version.
chris at mad-teaparty dot com
28-May-2003 12:10
Nice function. I did it the other way round:

function uncompress($srcName, $dstName) {
   $zp = gzopen($srcName, "r");
   while(!gzeof($zp))
       $string .= gzread($zp, 4096);
   gzclose($zp);

   $fp = fopen($dstName, "w");
   fwrite($fp, $string, strlen($string));
   fclose($fp);
}

uncompress("./myfile.txt.gz", "./myfile.txt");

A shorter approach would be:

function uncompress($srcName, $dstName) {
  $string = implode("", gzfile($srcName));
  $fp = fopen($dstName, "w");
  fwrite($fp, $string, strlen($string));
  fclose($fp);
}
devcontact at tech-island dot com
24-Mar-2003 03:47
The method of first reading the source file and then passing its content to the gzip function instead of simply the source and destination filename was a bit confusing for me.

So I have written a simple funtion you can use to compress files in the gzip format (gzip is readable by winzip like .zip files)

function compress($srcName, $dstName)
{
  $fp = fopen($srcName, "r");
  $data = fread ($fp, filesize($srcName));
  fclose($fp);

  $zp = gzopen($dstName, "w9");
  gzwrite($zp, $data);
  gzclose($zp);
}

// Compress a file
compress("/web/myfile.dat", "/web/myfile.gz");
mlevy at rgj dot com
12-Feb-2003 10:06
If you turn zlib.output_compression_level on, be advised that you shouldn't try to flush() the output in your scripts. PHP will add the gzip header but send the output uncompressed, which plays havoc with Mozilla. IE seems to handle it, though.
monte at ispi dot net
19-Apr-2001 01:02
An alternate way to handle gzip compression is to let the mod_gzip module of apache handle it. This seems to contradict the tutorial on phpbuilder.com saying that it won't compress php (or any dynamic) output, but mod_gzip as of version 1.3.17.1a works well for me.

Here is an example of an httpd.conf setup:

<IfModule mod_gzip.c>
mod_gzip_on                Yes
mod_gzip_dechunk            Yes
mod_gzip_minimum_file_size  300
mod_gzip_maximum_file_size  0
mod_gzip_maximum_inmem_size 100000
mod_gzip_keep_workfiles    No
mod_gzip_temp_dir          /tmp
mod_gzip_item_include      file \.html$
mod_gzip_item_include      file \.jsp$
mod_gzip_item_include      file \.php$
mod_gzip_item_include      file \.pl$
mod_gzip_item_include      mime ^text/.*
mod_gzip_item_include      mime ^application/x-httpd-php
mod_gzip_item_include      mime ^httpd/unix-directory$
mod_gzip_item_include      handler ^perl-script$
mod_gzip_item_include      handler ^server-status$
mod_gzip_item_include      handler ^server-info$
mod_gzip_item_exclude      mime ^image/.*
</IfModule>

This will automatically compress all output of your files with the .php extention or the x-httpd-php mime type. Be sure to have dechunk set to Yes.

<zip_readgzclose>
 Last updated: Tue, 21 Dec 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Mon Mar 14 08:13:06 2005 Local time zone must be set--see zic manual page