PHP ZipArchive Tutorial: Usage Guide
ZipArchive is a class in PHP for working with ZIP compression files, offering functions to create, open, read, add, update, delete, and extract ZIP files.
Here are some common usage examples of ZipArchive:
- Create an empty ZIP file:
$zip = new ZipArchive();
$zip->open('path/to/archive.zip', ZipArchive::CREATE);
$zip->close();
- Open a existing ZIP file.
$zip = new ZipArchive();
$zip->open('path/to/archive.zip');
- Add files to a ZIP file.
$zip->addFile('path/to/file.txt', 'file.txt');
- Add the directory and its contents to a ZIP file.
$zip->addEmptyDir('path/to/directory');
$zip->addGlob('path/to/directory/*');
- Extract files from a ZIP archive to a specific directory.
$zip->extractTo('path/to/destination');
- Retrieve a list of files from a ZIP file.
$fileList = [];
for ($i = 0; $i < $zip->numFiles; $i++) {
$fileList[] = $zip->getNameIndex($i);
}
- Remove files from a ZIP archive.
$zip->deleteName('file.txt');
- Close the ZIP file.
$zip->close();
These are just a few common usage examples of the ZipArchive class, there are many more methods available for use. For specific usage, refer to the ZipArchive class documentation in the official PHP manual: https://www.php.net/manual/en/class.ziparchive.php