簡體   English   中英

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

[英]How do you create a .gz file using PHP?

我想使用 PHP 對我的服務器上的文件進行 gzip 壓縮。 有沒有人有一個例子可以輸入一個文件並輸出一個壓縮文件?

這段代碼可以解決問題

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

此處的其他答案在壓縮期間將整個文件加載到內存中,這將導致大文件出現“內存不足”錯誤。 下面的函數在大文件上應該更可靠,因為它以 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; 
} 

此外,您可以使用 php 的包裝器,即壓縮器 只需對代碼進行最小的更改,您就可以在 gzip、bzip2 或 zip 之間切換。

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

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

compress.zlib://更改為 compress.zip://以進行 zip 壓縮 (請參閱此關於 zip 壓縮的答案的評論) ,或將compress.bzip2://更改為 bzip2 壓縮。

帶有gzencode() 的簡單單行

gzencode(file_get_contents($file_name));

這對很多人來說可能很明顯,但是如果您的系統上啟用了任何程序執行功能( execsystemshell_exec ),您可以使用它們來簡單地gzip文件。

exec("gzip ".$filename);

注意:在使用$filename變量之前一定要正確清理它,特別是如果它來自用戶輸入(但不僅如此)。 它可用於運行任意命令,例如通過包含類似my-file.txt && anothercommand (或my-file.txt; anothercommand )的內容。

如果您只想解壓縮文件,這可以工作並且不會導致內存問題:

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

這是一個改進的版本。 我擺脫了所有嵌套的 if/else 語句,從而降低了圈復雜度,通過異常更好地處理錯誤,而不是跟蹤布爾錯誤狀態,某些類型提示,如果文件具有 gz 擴展名,我將退出已經。 它在代碼行方面稍微長了一點,但可讀性更高。

/**
 * Compress a file using gzip
 *
 * Rewritten from Simon East's version here:
 * https://stackoverflow.com/a/22754032/3499843
 *
 * @param string $inFilename Input filename
 * @param int    $level      Compression level (default: 9)
 *
 * @throws Exception if the input or output file can not be opened
 *
 * @return string Output filename
 */
function gzcompressfile(string $inFilename, int $level = 9): string
{
    // Is the file gzipped already?
    $extension = pathinfo($inFilename, PATHINFO_EXTENSION);
    if ($extension == "gz") {
        return $inFilename;
    }

    // Open input file
    $inFile = fopen($inFilename, "rb");
    if ($inFile === false) {
        throw new \Exception("Unable to open input file: $inFilename");
    }

    // Open output file
    $gzFilename = $inFilename.".gz";
    $mode = "wb".$level;
    $gzFile = gzopen($gzFilename, $mode);
    if ($gzFile === false) {
        fclose($inFile);
        throw new \Exception("Unable to open output file: $gzFilename");
    }

    // Stream copy
    $length = 512 * 1024; // 512 kB
    while (!feof($inFile)) {
        gzwrite($gzFile, fread($inFile, $length));
    }

    // Close files
    fclose($inFile);
    gzclose($gzFile);

    // Return the new filename
    return $gzFilename;
}

壓縮文件夾以滿足任何人的需要

function gzCompressFile($source, $level = 9)
{
    $tarFile = $source . '.tar';

    if (is_dir($source)) {
        $tar = new PharData($tarFile);
        $files = scandir($source);
        foreach ($files as $file) {
            if (is_file($source . '/' . $file)) {
                $tar->addFile($source . '/' . $file, $file);
            }
        }
    }

    $dest = $tarFile . '.gz';
    $mode = 'wb' . $level;
    $error = false;
    if ($fp_out = gzopen($dest, $mode)) {
        if ($fp_in = fopen($tarFile, 'rb')) {
            while (!feof($fp_in))
                gzwrite($fp_out, fread($fp_in, 1024 * 512));
            fclose($fp_in);
        } else {
            $error = true;
        }
        gzclose($fp_out);
        unlink($tarFile);
    } else {
        $error = true;
    }
    if ($error)
        return false;
    else
        return $dest;
}

copy('file.txt', 'compress.zlib://' .'file.txt.gz'); 查看文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM