How do you create a .gz file using PHP?

2019-01-10 05:08发布

I would like to gzip compress a file on my server using PHP. Does anyone have an example that would input a file and output a compressed file?

7条回答
倾城 Initia
2楼-- · 2019-01-10 05:34

The other answers here load the entire file into memory during compression, which will cause 'out of memory' errors on large files. The function below should be more reliable on large files as it reads and writes files in 512kb chunks.

/**
 * GZIPs a file on disk (appending .gz to the name)
 *
 * From http://stackoverflow.com/questions/6073397/how-do-you-create-a-gz-file-using-php
 * Based on function by Kioob at:
 * http://www.php.net/manual/en/function.gzwrite.php#34955
 * 
 * @param string $source Path to file that should be compressed
 * @param integer $level GZIP compression level (default: 9)
 * @return string New filename (with .gz appended) if success, or false if operation fails
 */
function gzCompressFile($source, $level = 9){ 
    $dest = $source . '.gz'; 
    $mode = 'wb' . $level; 
    $error = false; 
    if ($fp_out = gzopen($dest, $mode)) { 
        if ($fp_in = fopen($source,'rb')) { 
            while (!feof($fp_in)) 
                gzwrite($fp_out, fread($fp_in, 1024 * 512)); 
            fclose($fp_in); 
        } else {
            $error = true; 
        }
        gzclose($fp_out); 
    } else {
        $error = true; 
    }
    if ($error)
        return false; 
    else
        return $dest; 
} 
查看更多
家丑人穷心不美
3楼-- · 2019-01-10 05:35

This code does the trick

// Name of the file we're compressing
$file = "test.txt";

// Name of the gz file we're creating
$gzfile = "test.gz";

// Open the gz file (w9 is the highest compression)
$fp = gzopen ($gzfile, 'w9');

// Compress the file
gzwrite ($fp, file_get_contents($file));

// Close the gz file and we're done
gzclose($fp);
查看更多
狗以群分
4楼-- · 2019-01-10 05:42

Simple one liner with gzencode():

gzencode(file_get_contents($file_name));
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-10 05:45

If you are looking to just unzip a file, this works and doesn't cause issues with memory:

$bytes = file_put_contents($destination, gzopen($gzip_path, r));
查看更多
疯言疯语
6楼-- · 2019-01-10 05:50

copy('file.txt', 'compress.zlib://' . 'file.txt.gz'); See documentation

查看更多
我想做一个坏孩纸
7楼-- · 2019-01-10 05:51

It's probably obvious to many, but if any of the program execution functions is enabled on your system (exec, system, shell_exec), you can use them to simply gzip the file.

exec("gzip ".$filename);

N.B.: Be sure to properly sanitize the $filename variable before using it, especially if it comes from user input (but not only). It may be used to run arbitrary commands, for example by containing something like my-file.txt && anothercommand (or my-file.txt; anothercommand).

查看更多
登录 后发表回答