2011-05-20 88 views

回答

69

这里的其他答案会在压缩过程中将整个文件加载到内存中,这将导致大文件上出现'内存不足'错误。下面的函数在大文件上应该更可靠,因为它以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; 
} 
+0

完美!正是我所需要的。 – Clox 2014-06-21 09:55:52

+0

你的代码的最好的一个! – Fuser97381 2014-10-14 16:50:50

+0

非常好的一点。我把上面并创造了逆解压缩的文件。该代码是相当快的。 – user3759531 2014-10-24 20:26:34

91

此代码的伎俩

// 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); 
+9

+1回答自己的问题:-) – 2011-05-20 14:37:36

+10

不幸的是这将可能将整个文件读入内存,可能打在大文件PHP的内存限制。 :-( – 2014-03-31 04:37:34

+0

虽然w9是最高压缩率,这是最低压缩率,只是用于包装数据.gz? – AMB 2017-01-23 16:06:41

19

此外,您可以使用PHP的wrapperscompression ones。只需对代码进行微小的更改,您就可以在gzip,bzip2或zip之间进行切换。

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

file_put_contents("compress.zlib://$output", file_get_contents($input)); 

变化为zip压缩compress.zlib:// compress.zip://(见注释这个答案约ZIP压缩) ,或 compress.bzip2://到的bzip2压缩。

+0

我认为压缩不支持compress.zip://'参见http:// www。 php.net/manual/en/wrappers.compression.php – Alex 2013-02-06 08:54:26

+0

@Alex是的,看起来你是对的,并且zip:// wrapper不支持写入,也不支持添加到已存在的文件 – 2013-02-06 11:12:06

5

简单的一个内胆采用gzencode()

gzencode(file_get_contents($file_name)); 
3

如果你正在寻找只是解压缩文件,这个作品,不与内存引起的问题:

$bytes = file_put_contents($destination, gzopen($gzip_path, r)); 
1

这可能很明显许多,但如果有任何程序执行功能的系统(execsystemshell_exec),你可以用它们来简体启用ly gzip该文件。

exec("gzip ".$filename); 
+0

高管被锁定在最托管平台,并在一般的安全风险,甚至使用EXEC – Wranorn 2018-01-16 09:08:28

+0

@Wranorn这就是为什么我指出:“如果任何的程序执行功能为e在你的系统上打个招呼,“我应该在你的主机平台上写下”而不是?至于安全性方面,如果你不把用户输入传递给这个函数,我不确定有什么风险。的[PHP文档]中唯一的警告(http://php.net/manual/en/function.exec.php)是关于使用'escapeshellarg()'或'escapeshellcmd()将'通过用户提供的数据到时功能。 – Niavlys 2018-01-16 12:46:04

相关问题