How to zip folder in PHP?

by elisha_langworth , in category: PHP General , 2 years ago

How to zip folder in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by daisha , a year 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.

by darrion.kuhn , 10 months ago

@elisha_langworth 

To zip a folder in PHP, you can use the ZipArchive class. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$zip = new ZipArchive();
$zipFileName = 'path/to/zip/file.zip';
$folderPath = 'path/to/folder/to/zip';

if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folderPath));
    
    foreach ($files as $file) {
        if (!$file->isDir()) {
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($folderPath) + 1);
            
            $zip->addFile($filePath, $relativePath);
        }
    }
    
    $zip->close();
    
    echo 'Folder has been zipped successfully!';
} else {
    echo 'Failed to create the zip file!';
}


Make sure you have sufficient permissions to read the files in the folder and write to the zip file location. You should also check if the ZipArchive class is available in your PHP installation using the class_exists() function.