How can the ZipArchive class in PHP be effectively used to create archives that maintain folder structures when extracted on different operating systems?
When creating ZIP archives in PHP using the ZipArchive class, it's important to set the correct flag to ensure that the folder structure is maintained when extracted on different operating systems. This can be achieved by using the ZipArchive::addFile() method with the ZIPARCHIVE::CREATE and ZIPARCHIVE::OVERWRITE flags.
$zip = new ZipArchive();
$zipFileName = 'archive.zip';
if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/directory'));
foreach ($files as $file) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen('path/to/directory') + 1);
$zip->addFile($filePath, $relativePath);
}
$zip->close();
echo 'Archive created successfully';
} else {
echo 'Failed to create archive';
}
Related Questions
- In what situations is it recommended to search for error messages in PHP using a search engine?
- When considering database normalization in PHP applications, what are the implications of not using a cross-table approach for linking users to multiple locations?
- What is the difference between SORT_REGULAR, SORT_NUMERIC, and SORT_STRING options when sorting an array in PHP?