Как создать файл .gz с помощью PHP?

Я хотел бы, чтобы gzip сжимал файл на моем сервере с помощью PHP. Есть ли у кого-нибудь пример, который будет вводить файл и выводить сжатый файл?

Другие ответы здесь загружают весь файл в память во время сжатия, что приведет к ошибкам « из памяти » в больших файлах. Функция, приведенная ниже, должна быть более надежной в больших файлах при чтении и записи файлов в блоках размером 512 КБ.

/** * 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; } 

Этот код делает трюк

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

Кроме того, вы можете использовать обертки php, сжатые . При минимальном изменении кода вы сможете переключаться между gzip, bzip2 или zip.

 $input = "test.txt"; $output = $input.".gz"; file_put_contents("compress.zlib://$output", file_get_contents($input)); 

смените compress.zlib:// на compress.zip:// для compress.zip:// zip (см. комментарий к этому ответу о сжатии zip) или compress.bzip2:// для сжатия bzip2.

Простой один вкладыш с gzencode () :

 gzencode(file_get_contents($file_name)); 

Если вы хотите просто разархивировать файл, это работает и не вызывает проблем с памятью:

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

Вероятно, это очевидно для многих, но если какая-либо из функций выполнения программы включена в вашей системе ( exec , system , shell_exec ), вы можете использовать их для простого gzip файла.

 exec("gzip ".$filename);