gzip and return as string

2.7k Views Asked by At

I want to compress some files with gzip in PHP..

It works as it should when the output file is saved into a file.. When the file is opened it looks like this

enter image description here

But not when the output is returned as a string.. Then the opened file looks like this.. Why is tar file showed inside the gzip file?

enter image description here

public function compress(){
    if($this->stream){
        return gzencode($this->data, 9);
    }
    else{
        $gz = gzopen('test.tar.gz', 'w9');
        gzwrite($gz, $this->data);
        gzclose($gz);
    }
}

headers sent with string output to the browser

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$filename.'"');
3

There are 3 best solutions below

0
On

I am sure that you looked into http://php.net/manual/en/function.gzcompress.php

make sure that you have php version PHP 4 >= 4.0.1, PHP 5

 string gzcompress ( string $data [, int $level = -1 [, int $encoding = ZLIB_ENCODING_DEFLATE ]] )

This function compress the given string using the ZLIB data format.

For details on the ZLIB compression algorithm see the document "» ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

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

Note:

This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

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_* constants.

gzencode — Create a gzip compressed string

<?php
$data = implode("", file("bigfile.txt"));
$gzdata = gzencode($data, 9);
$fp = fopen("bigfile.txt.gz", "w");
fwrite($fp, $gzdata);
fclose($fp);
?>
0
On

This looks like a WinRAR file extension parsing issue.

In the first example your file is called .tar.gz and WinRAR knows how to handle both tar files and gz compression, so it is able to decompress the tar headers in memory and retrieve a list of files contained within.

In your second example the file is called .tar-19.gz, so WinRAR happily deals with the gz compression but has no idea what format tar-19 is supposed to be (it doesn't even try and guess from header heuristics)

I bet if you stream the file with a tar.gz extension it will open up just fine.

0
On

Have you tried passing "Content-type: application/x-gzip" headers when sending the file as a string?

It's possible Apache is re-running it through a gzip filter and that's causing issues.