PHP: Hypertext Preprocessor (original) (raw)

gzcompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

gzcompress — Compress a string

Parameters

data

The data to compress.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression.

If -1 is used, the default compression of the zlib library is used which is 6.

encoding

One of [ZLIB_ENCODING_*](zlib.constants.php#constant.zlib-encoding-raw) constants.

Return Values

The compressed string or [false](reserved.constants.php#constant.false) if an error occurred.

Examples

Example #1 gzcompress() example

<?php $compressed = gzcompress('Compress me', 9); echo $compressed; ?>

See Also

Found A Problem?

@boas.anthro.mnsu.edu

24 years ago

`No, it doesn't return gzip compressed data -- specifically, the CRC is messed up. However, after massaging the output a lot, I have come up with a solution. I also commented it a lot, pointing out odd things.

Size=strlen(Size = strlen(Size=strlen(contents); Crc=crc32(Crc = crc32(Crc=crc32(contents);// Compress the data contents=gzcompress(contents = gzcompress(contents=gzcompress(contents, 9);// We can't just output it here, since the CRC is messed up. // If I try to "echo $contents" at this point, the compressed // data is sent, but not completely. There are four bytes at // the end that are a CRC. Three are sent. The last one is // left in limbo. Also, if we "echo $contents", then the next // byte we echo will not be sent to the client. I am not sure // if this is a bug in 4.0.2 or not, but the best way to avoid // this is to put the correct CRC at the end of the compressed // data. (The one generated by gzcompress looks WAY wrong.) // This will stop Opera from crashing, gunzip will work, and // other browsers won't keep loading indefinately. // // Strip off the old CRC (it's there, but it won't be displayed // all the way -- very odd) contents=substr(contents = substr(contents=substr(contents, 0, strlen($contents) - 4);// Show only the compressed data echo $contents;// Output the CRC, then the size of the original gzip_PrintFourChars($Crc); gzip_PrintFourChars($Size);// Done. You can append further data by gzcompressing // another string and reworking the CRC and Size stuff for // it too. Repeat until done.function gzip_PrintFourChars($Val) { for ($i = 0; i<4;i < 4; i<4;i ++) { echo chr($Val % 256); Val=floor(Val = floor(Val=floor(Val / 256); } } ?>

`

detain at interserver dot net

7 years ago

`gzipped strings include header/metadata you can use to determine if a string is gzipped or not , but since gzcompress does not include that I found myself needing a way to determine if a string was compressed or not. After some research (and then improvements) i came up with this:

/**

`