Reputation: 406
The function does not seem to be creating the ZIP file properly. The file prompt to downloads works fine. However when opening it, it just creates copy with .cpgz
format.
For reference:
foreach ($attachments as $file)
outputs as "/upload/image.jpg"
function downloadAttachment() {
$zipname = 'attachments.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($attachments as $file) {
$fileSrc = $_SERVER['DOCUMENT_ROOT'] . $file["file_attachment"];
$zip->addFile($fileSrc);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
ob_clean();
flush();
readfile($zipname);
}
Upvotes: 1
Views: 754
Reputation: 4202
You can use dirname(__FILE__)
- it return you absolute path to your current php script, make var_dump( dirname(__FILE__) )
to see what it gives you and then relocate with ../
or /folders/..
to your attachments directory
so your $zipname
will be something like $zipname = dirname(__FILE__) .'/../some_folders/attachements/attachments.zip'
;
and make sure that directory is writable by www-data
user or just chmod
it 0777
in any case
__FILE__
is one of PHP's magic constants you can check more here - http://php.net/manual/en/language.constants.predefined.php
one more good practice is to define somewhere in configs.php
which is included on every php define('ROOT_DIR', "absolute root path of your project");
then use ROOT_DIR
variable everywhere in your project as prefix for all folders ROOT_DIR."/folder/file ..."
Upvotes: 1