Hi i'm trying to force download a zip file created from ZipArchive()
but the file is not being downloaded instead is displayed/read in the browser.check my code below.
function search(item){
var search = new XMLHttpRequest();
search.open("POST","download.php");
search.onreadystatechange = function(){
if(search.readyState === 4 && search.status === 200){
// document.getElementById('tes').innerHTML = search.responseText;
}
}
search.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
search.send("searchItem="+item);
}
download button, calls search function.
<button value="<?php echo "$name"; ?>" onclick="search(this.value)">Download File</button>
PHP code in the download.php file
<?php
$name = trim($_POST['searchItem']);
if(!file_exists("images/$name/$name.zip")){
//creating a zip file
$zip = new ZipArchive();
$zip_file = "$name".'.zip';
$zip->open("images/$name/".$zip_file, ZipArchive::CREATE);
$files = scandir("images/$name/");
for ($i=2; $i < count($files) ; $i++) {
$fi = $files[$i];
if(file_exists("images/$name/$fi")){
$zip->addFile("images/$name/$fi", $fi);
}
}
$zip->close();
//force to download the zip
$file = "images/$name/$zip_file";
header("Pragma: public");
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="'.basename($file).'"');
readfile($file);
// remove zip file from temp path
unlink($file);
}
?>