To create a zip archive from a directory in PHP, you can use the ZipArchive
class. Here is an example:
// Directory to be zipped
$dirPath = 'path/to/directory';
// Path to save the zip file
$zipPath = 'path/to/save/archive.zip';
// Create a new zip archive
$zip = new ZipArchive();
// Open the zip file for writing
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
// Create recursive directory iterator
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dirPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
// Skip directories (we only want files)
if (!$file->isDir()) {
// Get the relative path of the file from the base directory
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($dirPath) + 1);
// Add the file to the zip archive with its relative path
$zip->addFile($filePath, $relativePath);
}
}
// Close the zip archive
$zip->close();
echo 'Zip archive created successfully!';
} else {
echo 'Failed to create zip archive!';
}
Make sure to replace 'path/to/directory'
with the directory path you want to zip, and 'path/to/save/archive.zip'
with the desired path to save the zip archive.
This code snippet recursively iterates through all files in the directory using RecursiveIteratorIterator
and RecursiveDirectoryIterator
. Then, it adds each file to the zip archive using addFile
method with its relative path.
If the zip archive is created successfully, it will display a success message; otherwise, it will display a failure message.