如何使用PHP创建.gz文件?

AlB*_*ebe 52 php compression gzip

我想使用PHP在我的服务器上压缩文件.有没有人有一个输入文件并输出压缩文件的例子?

AlB*_*ebe 97

这段代码可以解决问题

// 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);
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这可能会将整个文件读入内存,可能会影响PHP对大文件的内存限制.:-( (12认同)

Sim*_*ast 87

这里的其他答案在压缩期间将整个文件加载到内存中,这将导致大文件上的"内存不足 "错误.下面的函数在大文件上应该更可靠,因为它以512kb的块读取和写入文件.

/**
 * 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; 
} 
Run Code Online (Sandbox Code Playgroud)

  • 非常好的代码。我采用了上述内容并创建了相反的内容来解压缩文件。该代码相当快。 (3认同)
  • 压缩很酷,减压怎么样? (3认同)

Car*_*rós 20

此外,您可以使用php的包装器,压缩包装器.只需对代码进行最小的更改,您就可以在gzip,bzip2或zip之间切换.

$input = "test.txt";
$output = $input.".gz";

file_put_contents("compress.zlib://$output", file_get_contents($input));
Run Code Online (Sandbox Code Playgroud)

更改compress.zlib://compress.zip://为zip压缩 (看到这个答案约ZIP压缩评论),或者compress.bzip2://以压缩的bzip2.


dtb*_*rne 5

gzencode()的简单单线程:

gzencode(file_get_contents($file_name));
Run Code Online (Sandbox Code Playgroud)