Reputation: 5142
I have some pdf files...I want to just download them as a collection and not one by one. For that , I am trying to zip all pdf files and download. But I don't know why when in my code I am changing ZipArchive file name, it is saying damaged and corrupt. My code is below:-
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
//add each files of $file_name array to archive
foreach($file_names as $files)
{
$zip->addFile($file_path.$files,$files);
}
$zip->close();
//then send the headers to foce download the zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
}
if($button=="Save as pdf")
{
$file_names = array();
foreach($a as $key=>$as)
{
$file_names[] = $key.'.pdf';
}
}
$archive_file_name='zipped.zip';
$file_path='/resume/';
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
?>
Can anybody help me out? Thanks in advance.
Its working fine but still i am facing 2 problems,1. I am getting error that Archive is corrupted if I change the name of archive_file_name to something other than given above. I don't why its happening 2.If I have got a zip file of say, 2 pdfs and then i again download a zip of only 1 pdf which was not same as earlier ones. But when I am downloading the zip of 1 pdf, then i am getting 3 pdfs......I don't know why ........please help me.
Upvotes: 2
Views: 2659
Reputation: 8949
I tested your zipFilesAndDownload
function and it works well. So at first you should check your script, whether you have no characters or blank spaces sent before the <?php
starting tag.
In the case that your script is running inside a CMS, you should also clear all output buffers: while (@ob_end_clean());
(and if gzip headers was already sent, then also turn gz compression on again ob_start('ob_gzhandler');
)
Also you can also check, if you have correctly set the $file_path and all your files exists, for example:
$file_path='resume/';
if (!file_exists($file_path) || !is_dir($file_path)) {
die("Invalid directory $file_path in ".getcwd());
}
// you can test the existence of your problematic files:
foreach ($file_names as $file) {
if (!file_exists($file_path.$file)) {
echo "$file not found.";
} else {
echo "$file is ok.";
}
}
exit;
// end of test
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
In Windows is also problem with UTF-16/UTF-8/international character encoding, see here: PHP detecting filesystem encoding, How do I use filesystem functions in PHP, using UTF-8 strings?.
Upvotes: 1