Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Zip là một định dạng nén phổ biến, thường được sử dụng để giảm dung lượng của các loại tệp tin, để thuận tiện trong việc chia sẻ chúng với người khác hoặc lưu trữ. Trong PHP, bạn có thể sử dụng class ZipArchive để hỗ trợ việc nén một hoặc nhiều tệp tin vào một tệp tin zip duy nhất.

ZipArchive là một class có sẵn trong PHP, do đó bạn có thể sử dụng nó mà không cần cài đặt thêm bất kỳ thành phần nào.

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

Trả lời

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 *