I am using ZipArchive with PHP to create a .zip file in which to export all the files that users upload to the web. Within this file there are many folders, each folder corresponds to an ID and within each one there can be one or several files (images, .pdfs ...)
It is exported well and classified in folders, the problem I have is that there are files that do not have an extension and I would like it if a file does not have it, add it. I've thought about looking at the mimetype of the file and depending on that I add it, but I do not know how to put it. Besides, each file must always be renamed with the sequence for the name: id_of_your_folder + 01, id_of_your_folder + 02, and so on ...
How can I modify my code to add an extension in case I do not have it and make sure it is correctly renamed?
$zipname = 'nameofzip.zip';
$local_file = $dir_adjuntos . $zipname;
if(file_exists($local_file)){
$overwrite = true;
}
$zip = new ZipArchive;
$zip->open($local_file, $overwrite ? ZipArchive::OVERWRITE : ZipArchive::CREATE);
foreach ($files as $key => $file) {
$filepath = $this->getModel('Archive','ArchivesModel')->getFilenameWithFullPath($file);
$zip->addFile($filepath, 'nameofzip'.DS.$file->archive_id.DS.$file->filename);
}
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename='.basename($local_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($local_file));
ob_clean();
flush();
readfile($local_file);
die();
Example of output:
nameofzip/9201/8728(2).pdf --> debe ser: nameofzip/9201/9201_01.pdf
nameofzip/9202/8799(1) --> debe ser: nameofzip/9202/9202_01.pdf
nameofzip/9203/8802(1).jpg --> debe ser: nameofzip/9204/9203_01.jpg
nameofzip/9203/8802(2).jpg --> debe ser: nameofzip/9204/9203_02.jpg
nameofzip/9204/8839(1) --> debe ser: nameofzip/9204/9204_01.jpg