PHP | Rename all the files in zip and then extract zip in PHP

|
| By Webner

Description: In one of our PHP projects, we wanted to rename all the files in zip folder and then extract the zip.

The code for this is written below :

$zip = new ZipArchive;
$res = $zip->open($sourceFolder.'\'.$file);
for ($i = 0; $i < $zip->numFiles; $i++)
{
$filename = $zip->getNameIndex($i);
$newname;
$arr=explode('.',$file );
if(substr_count($arr[0],"_")==2)
{
$underscorearr=explode('_',$arr[0] );
$newname=$underscorearr[1].'_'.$underscorearr[2];
}
else
{
$newname=$arr[0];
}
$nameindex=$i+1;
$newname.='.00'.$nameindex;
$zip->renameName($filename,$newname);
}
$success=$zip->extractTo($sourceFolder);
$zip->close();

When we executed this code, it renamed all the files in the zip but did not extract. When we executed the code for second time, it extracted the zip files but did not rename the files in zip.

Solution : We modified the code as follows:

$zip = new ZipArchive;
$res = $zip->open($sourceFolder.'\'.$file);
for ($i = 0; $i < $zip->numFiles; $i++)
{
$filename = $zip->getNameIndex($i);
$newname;
$arr=explode('.',$file );
if(substr_count($arr[0],"_")==2)
{
$underscorearr=explode('_',$arr[0] );
$newname=$underscorearr[1].'_'.$underscorearr[2];
}
else
{
$newname=$arr[0];
}
$nameindex=$i+1;
$newname.='.00'.$nameindex;
$zip->renameName($filename,$newname);
}
$zip->close();
$zip1 = new ZipArchive;
$res1 = $zip1->open($sourceFolder.'\'.$file);
if($res1){
$success=$zip1->extractTo($sourceFolder);
}
$zip1->close();

The above code created two objects of ZipArchive. One object is used for renaming all the files and another is used for extracting the zip.

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

One comment

  1. Certainly a lot easier to extract to a temporary file then rename, Each time you renameName inside a zip file, the zip file has to be recreated. Ouch!

Leave a Reply

Your email address will not be published. Required fields are marked *