Hướng dẫn php zip folder and subfolders - thư mục zip php và các thư mục con

Dưới đây là một chức năng đơn giản có thể nén bất kỳ tệp hoặc thư mục nào một cách đệ quy, chỉ cần phần mở rộng zip được tải.

function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

Gọi nó như thế này:

Zip('/folder/to/compress/', './compressed.zip');

Hướng dẫn php zip folder and subfolders - thư mục zip php và các thư mục con

Đã trả lời ngày 26 tháng 8 năm 2009 lúc 14:07Aug 26, 2009 at 14:07

AXELALIX AXELALIXAlix Axel

149K92 Huy hiệu vàng390 Huy hiệu bạc496 Huy hiệu Đồng92 gold badges390 silver badges496 bronze badges

36

Tuy nhiên, một lưu trữ cây thư mục đệ quy khác, được triển khai như một phần mở rộng cho Ziparchive. Như một phần thưởng, một hàm trợ giúp nén cây một statement được bao gồm. Tên địa phương tùy chọn được hỗ trợ, như trong các hàm ziparchive khác. Mã xử lý lỗi sẽ được thêm vào ...

class ExtendedZip extends ZipArchive {

    // Member function to add a whole file system subtree to the archive
    public function addTree($dirname, $localname = '') {
        if ($localname)
            $this->addEmptyDir($localname);
        $this->_addTree($dirname, $localname);
    }

    // Internal function, to recurse
    protected function _addTree($dirname, $localname) {
        $dir = opendir($dirname);
        while ($filename = readdir($dir)) {
            // Discard . and ..
            if ($filename == '.' || $filename == '..')
                continue;

            // Proceed according to type
            $path = $dirname . '/' . $filename;
            $localpath = $localname ? ($localname . '/' . $filename) : $filename;
            if (is_dir($path)) {
                // Directory: add & recurse
                $this->addEmptyDir($localpath);
                $this->_addTree($path, $localpath);
            }
            else if (is_file($path)) {
                // File: just add
                $this->addFile($path, $localpath);
            }
        }
        closedir($dir);
    }

    // Helper function
    public static function zipTree($dirname, $zipFilename, $flags = 0, $localname = '') {
        $zip = new self();
        $zip->open($zipFilename, $flags);
        $zip->addTree($dirname, $localname);
        $zip->close();
    }
}

// Example
ExtendedZip::zipTree('/foo/bar', '/tmp/archive.zip', ZipArchive::CREATE);

Đã trả lời ngày 10 tháng 1 năm 2014 lúc 12:10Jan 10, 2014 at 12:10

1

Tôi đã chỉnh sửa câu trả lời của Alix Axel để thực hiện một bản phát âm thứ ba, khi đặt argroument thứ ba này thành

Zip('/folder/to/compress/', './compressed.zip');
7 Tất cả các tệp sẽ được thêm vào thư mục chính thay vì trực tiếp trong thư mục zip.

Nếu tệp zip tồn tại, tệp cũng sẽ bị xóa.

Example:

Zip('/path/to/maindirectory','/path/to/compressed.zip',true);

Cấu trúc zip thứ ba

Zip('/folder/to/compress/', './compressed.zip');
7:

maindirectory
--- file 1
--- file 2
--- subdirectory 1
------ file 3
------ file 4
--- subdirectory 2
------ file 5
------ file 6

Argrument thứ ba

Zip('/folder/to/compress/', './compressed.zip');
9 hoặc thiếu cấu trúc zip:

file 1
file 2
subdirectory 1
--- file 3
--- file 4
subdirectory 2
--- file 5
--- file 6

Mã đã chỉnh sửa:

function Zip($source, $destination, $include_dir = false)
{

    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    if (file_exists($destination)) {
        unlink ($destination);
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }
    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {

        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        if ($include_dir) {

            $arr = explode("/",$source);
            $maindir = $arr[count($arr)- 1];

            $source = "";
            for ($i=0; $i < count($arr) - 1; $i++) { 
                $source .= '/' . $arr[$i];
            }

            $source = substr($source, 1);

            $zip->addEmptyDir($maindir);

        }

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

Đã trả lời ngày 13 tháng 2 năm 2013 lúc 5:17Feb 13, 2013 at 5:17

user2019515user2019515user2019515

4,4451 Huy hiệu vàng28 Huy hiệu bạc42 Huy hiệu đồng1 gold badge28 silver badges42 bronze badges

5

Cách sử dụng: ThisFile.php? Dir =./Path/to/thư mục (sau khi zipping, nó cũng bắt đầu tải xuống :)thisfile.php?dir=./path/to/folder (After zipping, it starts download too:)

addEmptyDir($name);
        $name .= '/';
        $location.= '/';
        $dir = opendir ($location);   // Read all Files in Dir

        while ($file = readdir($dir)){
            if ($file == '.' || $file == '..') continue;
            if (!in_array($name.$file,$prohib_filenames)){
                if (filetype( $location . $file) == 'dir'){
                    $this->addDirDoo($location . $file, $name . $file,$prohib_filenames );
                }
                else {
                    $this->addFile($location . $file, $name . $file);
                }
            }
        }
    }

    public function downld($zip_name){
        ob_get_clean();
        header("Pragma: public");   header("Expires: 0");   header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);    header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=" . basename($zip_name) . ";" );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($zip_name));
        readfile($zip_name);
    }
}

//set memory limits
set_time_limit(3000);
ini_set('max_execution_time', 3000);
ini_set('memory_limit','100M');
$new_zip_filename='down_zip_file_'.rand(1,1000000).'.zip';  
// Download action
if (isset($_GET['dir']))    {
    $za = new ModifiedFlxZipArchive;
    //create an archive
    if  ($za->open($new_zip_filename, ZipArchive::CREATE)) {
        $za->addDirDoo($_GET['dir'], basename($_GET['dir']), $exclude_some_files); $za->close();
    }else {die('cantttt');}

if (isset($_GET['dir']))    {
    $za = new ModifiedFlxZipArchive;
    //create an archive
    if  ($za->open($new_zip_filename, ZipArchive::CREATE)) {
        $za->addDirDoo($_GET['dir'], basename($_GET['dir']), $exclude_some_files); $za->close();
    }else {die('cantttt');}

    //download archive
    //on the same execution,this made problems in some hostings, so better redirect
    //$za -> downld($new_zip_filename);
    header("location:?fildown=".$new_zip_filename); exit;
}   
if (isset($_GET['fildown'])){
    $za = new ModifiedFlxZipArchive;
    $za -> downld($_GET['fildown']);
}
?>

Đã trả lời ngày 7 tháng 2 năm 2014 lúc 15:41Feb 7, 2014 at 15:41

Hướng dẫn php zip folder and subfolders - thư mục zip php và các thư mục con

T.ToduaT.ToduaT.Todua

50,5K19 Huy hiệu vàng219 Huy hiệu bạc217 Huy hiệu đồng19 gold badges219 silver badges217 bronze badges

Hãy thử liên kết này

/** Include the Pear Library for Zip */
include ('Archive/Zip.php');

/** Create a Zipping Object...
* Name of zip file to be created..
* You can specify the path too */
$obj = new Archive_Zip('test.zip');
/**
* create a file array of Files to be Added in Zip
*/
$files = array('black.gif',
'blue.gif',
);

/**
* creating zip file..if success do something else do something...
* if Error in file creation ..it is either due to permission problem (Solution: give 777 to that folder)
* Or Corruption of File Problem..
*/

if ($obj->create($files)) {
// echo 'Created successfully!';
} else {
//echo 'Error in file creation';
}

?>; // We'll be outputting a ZIP
header('Content-type: application/zip');

// It will be called test.zip
header('Content-Disposition: attachment; filename="test.zip"');

//read a file and send
readfile('test.zip');
?>;

Đã trả lời ngày 26 tháng 8 năm 2009 lúc 13:20Aug 26, 2009 at 13:20

Phill Paffordphill PaffordPhill Pafford

82.1K90 Huy hiệu vàng260 Huy hiệu bạc380 Huy hiệu đồng90 gold badges260 silver badges380 bronze badges

Đây là mã của tôi cho zip các thư mục và các thư mục phụ của nó và các tệp của nó và làm cho nó có thể tải xuống ở định dạng zip

function zip()
 {
$source='path/folder'// Path To the folder;
$destination='path/folder/abc.zip'// Path to the file and file name ; 
$include_dir = false;
$archive = 'abc.zip'// File Name ;

if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
}

if (file_exists($destination)) {
    unlink ($destination);
}

$zip = new ZipArchive;

if (!$zip->open($archive, ZipArchive::CREATE)) {
    return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{

    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    if ($include_dir) {

        $arr = explode("/",$source);
        $maindir = $arr[count($arr)- 1];

        $source = "";
        for ($i=0; $i < count($arr) - 1; $i++) { 
            $source .= '/' . $arr[$i];
        }

        $source = substr($source, 1);

        $zip->addEmptyDir($maindir);

    }

    foreach ($files as $file)
    {
        $file = str_replace('\\', '/', $file);

        // Ignore "." and ".." folders
        if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
            continue;

        $file = realpath($file);

        if (is_dir($file) === true)
        {
            $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
        }
        else if (is_file($file) === true)
        {
            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
        }
    }
}
else if (is_file($source) === true)
{
    $zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
}

Nếu có bất kỳ vấn đề với mã cho tôi biết.

Đã trả lời ngày 26 tháng 6 năm 2014 lúc 9:39Jun 26, 2014 at 9:39

Nitinnitinnitin

7910 Huy hiệu đồng10 bronze badges

Tôi cần chạy chức năng zip này trong Mac OSX

Vì vậy, tôi sẽ luôn luôn zip gây phiền nhiễu đó .ds_store.

Tôi đã điều chỉnh https://stackoverflow.com/users/2019515/user2019515 bằng cách bao gồm các tệp bổ sung.

Zip('/folder/to/compress/', './compressed.zip');
0

Vì vậy, để bỏ qua .ds_store từ zip, bạn chạy

zipit ('/path/to/thư mục', '/path/to/compress.zip', false, mảng ('. ds_store'));

Đã trả lời ngày 1 tháng 3 năm 2013 lúc 7:58Mar 1, 2013 at 7:58

Kim Stackskim StacksKim Stacks

10.1K32 Huy hiệu vàng146 Huy hiệu bạc273 Huy hiệu Đồng32 gold badges146 silver badges273 bronze badges

Giải pháp tuyệt vời nhưng đối với các cửa sổ của tôi, tôi cần thực hiện một sửa đổi. Bên dưới mã sửa đổi

Zip('/folder/to/compress/', './compressed.zip');
1

Đã trả lời ngày 18 tháng 10 năm 2014 lúc 20:52Oct 18, 2014 at 20:52

JuanjuanJuan

1.9813 huy hiệu vàng21 Huy hiệu bạc34 Huy hiệu đồng3 gold badges21 silver badges34 bronze badges

Mã này hoạt động cho cả Windows và Linux.

Zip('/folder/to/compress/', './compressed.zip');
2

Đã trả lời ngày 23 tháng 2 năm 2016 lúc 8:46Feb 23, 2016 at 8:46

Ammar Qalaammar QalaAmmar Qala

631 Huy hiệu bạc8 Huy hiệu đồng1 silver badge8 bronze badges

Đây là cơ sở phiên bản của tôi trên Alix, hoạt động trên Windows và hy vọng trên *NIX cũng vậy:

Zip('/folder/to/compress/', './compressed.zip');
3

Đã trả lời ngày 20 tháng 8 năm 2017 lúc 17:32Aug 20, 2017 at 17:32

Ohad Schneiderohad SchneiderOhad Schneider

35K13 Huy hiệu vàng161 Huy hiệu bạc195 Huy hiệu Đồng13 gold badges161 silver badges195 bronze badges

Dưới đây là hàm đệ quy đơn giản, dễ đọc, hoạt động rất tốt:

Zip('/folder/to/compress/', './compressed.zip');
4

Đã trả lời ngày 25 tháng 12 năm 2017 lúc 20:50Dec 25, 2017 at 20:50

TariktarikTarik

4.05237 Huy hiệu bạc33 Huy hiệu đồng37 silver badges33 bronze badges

Theo sau @user2019515 Trả lời, tôi cần xử lý các loại trừ cho kho lưu trữ của mình. Đây là chức năng kết quả với một ví dụ.

Chức năng zip:

Zip('/folder/to/compress/', './compressed.zip');
5

Làm thế nào để sử dụng nó :

Zip('/folder/to/compress/', './compressed.zip');
6

Đã trả lời ngày 26 tháng 2 năm 2020 lúc 16:37Feb 26, 2020 at 16:37

Làm thế nào để tạo một zip thư mục trong PHP?

Đặt các tệp PHP cùng với thư mục sẽ được nén trong C: \ Xampp \ HTDOCS (XAMPP được cài đặt trong ổ C: trong trường hợp này).Trong trình duyệt, nhập https: //localhost/zip.php dưới dạng URL và tệp sẽ được nén.Sau đó, một tệp zip mới được tạo có tên là 'tệp'.

Làm thế nào để bạn tạo một tệp zip đệ quy?

Cú pháp: $ zipTHERM FileName.zip Tệp.txt 4. -R Tùy chọn: Để zip một thư mục đệ quy, sử dụng tùy chọn -R với lệnh zip và nó sẽ đệ quy các tệp trong một thư mục.Tùy chọn này giúp bạn zip tất cả các tệp có trong thư mục được chỉ định.use the -r option with the zip command and it will recursively zips the files in a directory. This option helps you to zip all the files present in the specified directory.

Php ziparchive là gì?

Phương thức Ziparchive trong PHP được sử dụng để thêm tệp, thư mục mới và có thể đọc zip trong PHP.used to add the file, new directory, and able to read the zip in PHP.

Làm thế nào tải xuống tất cả các tệp từ thư mục trong PHP?

PHP $ name = $ _get ['nama'];Tải xuống ($ name);Tải xuống chức năng ($ name) {$ file = $ nama_fail;if (file_exists ($ file)) {header ('nội dung mô tả: chuyển tệp');Tiêu đề ('loại nội dung: Ứng dụng/-dòng octet');Tiêu đề ('Xác định nội dung: tệp đính kèm; fileName ='.