programing

PHP를 이용하여 .gz 파일을 만드는 방법은 무엇입니까?

oldcodes 2023. 10. 1. 21:55
반응형

PHP를 이용하여 .gz 파일을 만드는 방법은 무엇입니까?

PHP를 이용하여 서버에 파일을 압축하고 싶습니다.파일을 입력하고 압축 파일을 출력하는 예시가 있는 사람이 있습니까?

이 코드는 효과가 있습니다.

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

업데이트: Gerben은 오류에 대해 거짓으로 반환하는 대신 더 깨끗하고 예외를 사용하는 이 기능의 개선된 버전을 게시했습니다.https://stackoverflow.com/a/56140427/195835 참조

그리고 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 압축에 대한답변에 대한 코멘트 참조) 또는 다음을 수행합니다.compress.bzip2://bzip2 압축입니다.

gzencode()가 포함된 간단한 하나의 라이너:

gzencode(file_get_contents($file_name));

여기 개선된 버전이 있습니다.중첩된 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;
}

파일의 압축을 풀기만 하면 메모리에 문제가 발생하지 않습니다.

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

많은 사람들에게 분명할 것이지만, 시스템에서 프로그램 실행 기능이 활성화되어 있는 경우 (exec,system,shell_exec), 간단히 사용할 수 있습니다.gzip서류철

exec("gzip ".$filename);

N.B.: 반드시 적절한 위생 조치를 취해야 합니다.$filename사용하기 전 변수(특히 사용자 입력에서 나온 경우에만 해당됨).예를 들어 다음과 같은 것을 포함함으로써 임의의 명령을 실행하는 데 사용될 수 있습니다.my-file.txt && anothercommand(또는my-file.txt; anothercommand).

(' 파일을 복사합니다.txt', 'compress.zlib://' . file.txt.gz'); 설명서 참조

필요한 모든 사용자를 위해 폴더 압축

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

언급URL : https://stackoverflow.com/questions/6073397/how-do-you-create-a-gz-file-using-php

반응형