zip và unzip file và folder trong PHP


zip là một định dạng nén phổ biến, được sử dụng để làm giảm dung lượng các định dạng file, để có thể dễ dàng gửi chúng đi nơi khác. PHP sử dụng class ZipArchive để hỗ trợ nén một hoặc nhiều file tới một file zip.
ZipArchive là class built-in của PHP nên bạn có thể dễ dàng gọi chúng mà không phải thực hiện bất cứ một cài đặt gì.

Zip 1 file

<?php
// Init ZipArchive
$zipArchive = new ZipArchive();

// open zip file
if ($zipArchive->open('output/data.zip', ZipArchive::CREATE || ZipArchive::OVERWRITE)) {
    // Add files
    if (!$zipArchive->addFile('data/test-1.txt', 'test-1.txt')) {
        printf("zip file error");
        exit;
    }
} else {
    printf('Open file error');
    exit;
}

// Close ZipArchive
$zipArchive->close();

Kết quả:

Zip 1 folder

<?php
// Init ZipArchive
$zipArchive = new ZipArchive();

// open zip file
if ($zipArchive->open('output/data.zip', ZipArchive::CREATE || ZipArchive::OVERWRITE)) {

    // Add folder
    $dir = opendir('data/');
    while($file = readdir($dir)) {
        if(is_file("data/${file}")) {
            if (!$zipArchive->addFile("data/${file}", $file)) {
                printf("zip file error");
                exit;
            }
        }
    }

} else {
    printf('Open file error');
    exit;
}

// Close ZipArchive
$zipArchive->close();

Kết quả:

Unzip file

<?php
// Init ZipArchive
$zipArchive = new ZipArchive();

// open zip file
if ($zipArchive->open('output/data.zip')) {
    // Extracts to current directory
    $zipArchive->extractTo('./');
} else {
    printf('Open file error');
    exit;
}

// Close ZipArchive
$zipArchive->close();

Nguồn: vinasupport.com

             
SHARE

Bài viết liên quan

mode_edit Bình luận của bạn

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

account_circle
web