I am trying to take doc,pdf,docx files from MySQL database and zip all the document files together. The problem that I am facing is that I am able to download only one file and unable to ZIP any file as a matter of fact. Please help me in this regard.
<?php
if(isset($_GET['id']) && isset($_REQUEST['clickit']))
{
$id = intval($_GET['id']);
if($id <= 0){
die('The ID is invalid!');
}else{
$username = "";
$password = "";
$servername = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password,$dbname);
if (!$conn){
die("Connection failed: " . mysqli_connect_error());
}
Here I have taken all the columns in the table 'tbl_uploads_1' and passed that to result.
$sql = "SELECT * FROM tbl_uploads_1 ";
$result = $conn->query($sql);
$files = array();
Here I am taking records from column named 'file_name' from the table in the database which has filenames stored like 'abc.doc'. I am not sure if the code below is the right flow to distinguish between docs with different extensions.
while($row = $result->fetch_assoc()) {
$filename = $row["file_name"];
$ext1 = end((explode(".", $filename)));
if($ext1 == pdf){
$files[] = "$filename.pdf";
} else if($ext1 == docx){
$files[] = "$filename.docx";
} else if($ext1 == doc){
$files[] = "$filename.doc";
}
//if ( file_put_contents("$filename.pdf", $content) === FALSE ) {
//echo "Could not write PDF File";
//}
}
Here is the zipping part of the code. Please review this.
$zipfilename = 'temp_' . time() . '.zip';
$zip->open($zipfilename, ZipArchive::CREATE);
foreach ($files as $file){
$zip->addFile($file);
}
$zip->close();
Should I include header methods for every file before we zip??
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=filename.zip');
header('Content-Length: ' . filesize($zipfilename));
readfile($zipfilename);
}
//else{
//echo "Err!!";
//}
$conn->close();
}
exit();
?>