How to zip folder in PHP?

by elisha_langworth , in category: PHP General , 9 months ago

How to zip folder in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 3 months ago

@elisha_langworth 

To zip a folder using PHP, you can use the ZipArchive class. Here is an example of how to use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php

// create new zip archive
$zip = new ZipArchive();

// specify the path to the zip file and create it
$zipFile = 'path/to/zipfile.zip';
$zip->open($zipFile, ZipArchive::CREATE);

// specify the path to the folder that you want to zip
$folderToZip = 'path/to/folder';

// add the folder to the zip archive
$zip->addEmptyDir($folderToZip);

// create a recursive iterator for the folder
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($folderToZip),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($folderToZip) + 1);

        // add current file to the zip archive
        $zip->addFile($filePath, $relativePath);
    }
}

// close the zip archive
$zip->close();

?>


This code will create a new zip file at the specified path and add the contents of the specified folder to it. The files and subfolders in the folder will be added recursively, so all the files and subfolders in the folder and its subfolders will be added to the zip file.


Note that this code requires PHP version 5.2 or higher.