How to extract zip archive with file rename if there are duplicates in the destination folder (PHP)
This is an example of a function that extracts files from an archive, renaming them if there are files with the same name in the destination folder:
function extractZip($zipFilePath, $folderToExtract)
{
$zipArchive = new ZipArchive();
$result = $zipArchive->open($zipFilePath);
if ($result === TRUE) {
for ($i = 0; $i < $zipArchive->numFiles; $i++) {
$filename = $zipArchive->getNameIndex($i);
$filePath = $folderToExtract. '/' . $filename;
if (file_exists($filePath)) {
$fileInfo = pathinfo($filename);
$newFileName = $fileInfo['filename'] . '_(copy).' . $fileInfo['extension'];
copy("zip://" . $zipFilePath . "#" . $filename, $folderToExtract . '/' . $newFileName);
} else {
copy("zip://" . $zipFilePath. "#" . $filename, $filePath);
}
}
$zipArchive->close();
}
}
Function parameters:
$zipFilePath - path to zip file
$folderToExtract - path to the folder where the archive should be unpacked.
It should be noted that the function has not been tested on nested archives and nested folders.
Comments