-1

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();
?>
  • 4
    Take a look at [ask]. You need to be able to describe your specific problem, what you've done to try to solve it, what happened, what you expected to happen, how they differ, what specific errors you got, etc. Just dumping in a blob of code and saying it doesn't work makes it difficult for anyone to help you. – pvg May 30 '17 at 07:49
  • Possible duplicate of [Download multiple files as a zip-file using php](https://stackoverflow.com/questions/1754352/download-multiple-files-as-a-zip-file-using-php) – Nidhi May 30 '17 at 08:49
  • @Nidhi I want to zip the files directly from the database and not from the local filesystem. – Anoop Madamsetty May 30 '17 at 09:05
  • Are your files upload in your project folder? you just get a name from DB ? is it so?@AnoopMadamsetty – Nidhi May 30 '17 at 09:56
  • @Nidhi I am using MySQL Database and documents are stored as a BLOB in the same. – Anoop Madamsetty May 30 '17 at 10:55
  • Try my demo code for make zip of DB documents@AnoopMadamsetty – Nidhi May 31 '17 at 04:55
  • At least you should reply if you post your question here.So both the questioner and the answering agent know the solution@AnoopMadamsetty – Nidhi Jun 05 '17 at 12:02
  • @Nidhi I did not require to zip anymore...so did not test it...and i did not accept the answer as I did not want to mislead people...i ll try and update later..please be little patient – Anoop Madamsetty Jun 05 '17 at 12:17

1 Answers1

0

Try this code for download files from database

$sql = "SELECT * FROM table_name";
if ($result=mysqli_query($conn,$sql))
{    
    // $rowcount=mysqli_num_rows($result);
    // printf("Result set has %d rows.\n",$rowcount);
    //define array for storing files
    $file = array(); 
    while ($row = mysqli_fetch_assoc($result)) {   
        //give file name with extension    
        $name = $_SERVER['DOCUMENT_ROOT']."/demo/mysql_blob/files/".$row['file_name'];
        //store file name in array
        $file[] = $name;
        // store file in one folder named 'files'
        file_put_contents($name,$row["fileData"]);

    }
    $zipname = 'file.zip';
    $zip = new ZipArchive;

    //open zip file and put all files in zip
    foreach ($file as $f) {
        if($zip->open($zipname, ZipArchive::CREATE) === TRUE) {
            $new_filename = substr($f,strrpos($f,'/') + 1);
            $zip->addFile($f,$new_filename);
            echo "ok";
        } else {
            echo "fail";
        }
    }
    if ($zip->close() === false) {
       exit("Error creating ZIP file");
    }
    //check zip file create or not and download it
    if (file_exists($zipname)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename='.basename($zipname));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($zipname));
        ob_clean();
        flush();
        readfile($zipname);
        exit;
    } else {
        exit("Could not find Zip file to download");
    }
    mysqli_free_result($result);
    mysqli_close($conn);
}
Nidhi
  • 1,529
  • 18
  • 28