|
 |
CLXX. Функции сжатия Zlib
Этот модуль позволяет работать со сжатыми файлами gzip (.gz) стандартным
методом, наподобие функций файловой системы
(исключение составляют только сокеты).
Замечание:
В версии 4.0.4 появился новый протокол 'zlib:' для доступа прямого к сжатым
файлам через обычные функции f*() (для этого нужно было добавить 'zlib:'
в начало пути к файлу при вызове fopen().
В версии 4.3.0, префикс изменился на 'zlib://' для предотвращения многозначности
в случае файлов, содержащих ':' в имени.
Требуется библиотека времени выполнения C, предоставляющая функцию fopencookie().
Насколько нам известно, такой библиотекой является только GNU libc.
Этот модуль использует библиотеку zlib,
написанную Jean-loup Gailly и Mark Adler. Используйте версию zlib >= 1.0.9 с этим модулем.
Поддержка Zlib при стандартной сборке PHP отсутствует. Чтобы изменить это, добавьте ключ --with-zlib[=DIR] при запуске сценария ./configure
Версия PHP для
Windows имеет встроенную поддержку данного расширения. Это означает, что
для использования данных функций не требуется загрузка никаких
дополнительных расширений. Замечание:
Т.к. библиотека zlib отсутствует в Windows, она встроена в PHP начиная с версии 4.3.0.
Поведение этих функций зависит от установок в php.ini.
Модуль zlib предоставляет возможность сжатия передаваемых страниц (в т.ч. динамических)
на лету, если браузер это поддерживает. За сжатие отвечают три параметра в конфигурационном файле php.ini.
Таблица 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
Сжимать ли страницы. Если значение равно "On" в php.ini или в настройках Apache,
страницы будут сжиматься если обозреватель посылает заголовок "Accept-Encoding: gzip" или
"deflate". при этом в вывод будут добавлены заголовки "Content-Encoding: gzip" (соответственно
"deflate") и "Vary: Accept-Encoding".
Аргументы также могут быть целого типа, так вы можете установить размер буфера
(дискретизации) вывода (по умолчанию 4 Кб).
Замечание:
output_handler должен быть
пустым, если выбрано значение 'On'! Вместо него следует использовать zlib.output_handler.
- zlib.output_compression_level
integer
Уровень сжатия.
- zlib.output_handler
string
Если zlib.output_compression активировано здесь, указывать дополнительные
обработчики вывода (output handlers) нельзя. Этот параметр делает то же,
что и output_handler, но в другом
порядке.
Данное расширение не определяет никакие типы ресурсов.
Перечисленные ниже константы определены данным расширением и могут быть
доступны только в том случае, если PHP был собран с
поддержкой этого расширения или же в том случае, если
данное расширение подгружается во время выполнения.
Здесь открывается временный файл, в него записывается строка, затем дважды печатается содержимое этого файла.
Пример 1. Небольшой пример использования Zlib
<?php
$filename = tempnam('/tmp', 'zlibtest') . '.gz';
echo "<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");
echo gzread($zp, 3);
gzpassthru($zp);
gzclose($zp);
echo "\n";
if (readgzfile($filename) != strlen($s)) {
echo "Error with zlib functions!";
}
unlink($filename);
echo "</pre>\n</body>\n</html>\n";
?>
|
|
- Содержание
- gzclose -- Закрывает открытый gz-указатель
- gzcompress -- Сжимает строку
- gzdeflate -- Сжимает строку
- gzencode -- Сжимает строку в формате gzip
- gzeof -- Проверяет, находится ли текущая позиция в конце gz-файла
- gzfile -- Считывает весь gz-файл в массив
- gzgetc -- Возвращает символ из gz-файла
- gzgets -- Возвращает строку из gz-файла
- gzgetss --
Возвращает строку из gz-файла с удалёнными HTML-тегами
- gzinflate -- Распаковывает строку
- gzopen -- Открывает gz-файл
- gzpassthru --
Выводит все оставшиеся данные из указателя gz-файла.
- gzputs -- Псевдоним gzwrite()
- gzread -- Бинарное чтение gz-файла
- gzrewind -- Перемещает индикатор позиции в gz-файле в начало
- gzseek -- Перемещает индикатор позиции в gz-файле
- gztell -- Возвращает текущую позицию чтения/записи в gz-файле
- gzuncompress -- Распаковывает строку
- gzwrite -- Бинарная запись в gz-файл
- readgzfile -- Выводит содержимое gz-файла
- zlib_get_coding_type -- Возвращает тип кодирования, используемый для сжатия вывода
Функции сжатия Zlib
php at seven dot net dot nz
07-Jul-2006 01:49
zlib.output_compression has caused problems for me in IE 6, when pages are sometimes not displayed. This could be difficult to track down and PHP have no intention of fixing it, so hopefully you find this note in a search if it happens to you.
http://bugs.php.net/bug.php?id=38026
Arne dot Heizmann at csr dot com
23-May-2006 10:34
PHP Version 5.1.4 here. What Bob said is correct even in this version (newest at the time of writing). You can't enable zlib.output_compression via ini_set(). You have to use php.ini.
Bob
19-Sep-2005 06:45
Contrary to what the documentation says, I've been unable to get zlib.output_compression to work via ini_set() (Even though I put it at the very beginning of the file before any output was sent) as of php 4.3.11. While it does get set to true, it will not actually do anything. Which means if you don't set this via php.ini or Apache configuration it's a no-go. I have to use ob_start("ob_gzhandler"); instead.
djmaze(AT)dragonflycms(.)org
27-Aug-2005 08:27
If you need to compress data and send it as "Content-disposition: attachment" and on-the-fly to the client due to the size for example (40Mb) here's a dirty trick using ob_gzhandler()
Keep in mind that $str is the content to output.
When you start the output call
<?php
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_START);
?>
Then to output any further content
<?php
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_CONT);
?>
And to close the output
<?php
echo ob_gzhandler('', PHP_OUTPUT_HANDLER_END);
exit;
?>
Only tested on Apache 1.3.33 with PHP 5.0.4
ghassler at speakeasy dot net
03-Jul-2005 09:45
I tested all the compression levels against a 22k page and here are the results I got (in bytes):
off = 22549
1 = 4297
2 = 4279
3 = 4264
4 = 4117
5 = 4097
6 = 4063
7 = 4011
8 = 3998
9 = 3996
Looks like the best bets for zlib.output_compression_level is 1 or 5. The default of 6 is probably OK too. Don't know what the CPU usage difference is between them all though.
jpleveille at webgraphe dot com
10-Jun-2005 06:08
register_shutdown_function() (register_shutdown_function) won't output anything if you use zlib.output_compression.
Shutdown function is called after closing all opened output buffers thus, for example, its output will not be compressed if zlib.output_compression is enabled.
admin_at_commandline_dot_ch
08-Oct-2004 05: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
13-Jul-2004 08: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 03: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 07:52
Have a look to this extended version :)
<?php
function compress( $srcFileName, $dstFileName )
{
$fp = fopen( $srcFileName, "r" );
$data = fread ( $fp, filesize( $srcFileName ) );
fclose( $fp );
$zp = gzopen( $dstFileName, "w9" );
gzwrite( $zp, $data );
gzclose( $zp );
}
function uncompress( $srcFileName, $dstFileName, $fileSize )
{
$zp = gzopen( $srcFileName, "r" );
$data = fread ( $zp, $fileSize );
gzclose( $zp );
$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 11: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
13-May-2004 07: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 04: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
27-May-2003 05: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 07: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 02: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
18-Apr-2001 06: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.
| |