I'm trying to write code to zip a file and download it. My problem is when I download and open the file, I get the error
The archive is either in unknown format or damaged
Here's my code:
<?php
try{
$db_conn = new DBController();
$db_conn->prepare("SELECT filetypename FROM dirlistening WHERE dadroot = :BasName AND sonbas = :BasDirName");
$db_conn->bind(':BasName', $parentBasIndex);
$db_conn->bind(':BasDirName', $currentBas);
$db_conn->execute();
$dbzipoutput = $db_conn->getAll();
$db_conn->free();
$files = array();
if(!is_null($dbzipoutput)){
foreach($dbzipoutput as $azip){
$files[] = $azip->filetypename;
}
}
//$file_names = array("'" . implode( $filess, "','" ) . "'");
$file_names = $files;
function zipSourceFilesDownload($file_names,$archive_file_name,$file_path){
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE){
exit("cannot open ".$archive_file_name."
");
}else{
foreach($file_names as $filelist){
$zip->addFile($file_path.'/'.$filelist);
$zip->addEmptyDir($file_path.'/'.$filelist);
$zip->addFromString($file_path.'/'.$filelist, file_get_contents($file_path.'/'.$filelist));
$zip->setArchiveComment("zipped on ".date('Y-M-d')."
Downloaded from: My website
Website: http://www.example.com
Project Source: ".$file_path."
Project Url: http://example.com" . $_SERVER['REQUEST_URI']."
FILE COMMENT AND DESCRIPTION
none");
}
$var = $zip->close();
$download_file = true;
}
if($download_file){
ob_get_clean();
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/zip");
header('Content-disposition: attachment; filename='.$archive_file_name);
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($archive_file_name));
print $zip_file;
unlink($archive_name);
}
return $var;
}
zipSourceFilesDownload($file_names,$archive_file_name,$file_path);
}catch (PDOException $e){ echo 'Connection failed: ' . $e->getMessage();}