0

How do I add a generated excel file to a password protected zip and download it? I am using ZipArchive library. I am trying to add the excel file to zip but unfortunately zip is not getting generated.

if(isset($_POST["export_excel"]))
{
    $sql = "SELECT * FROM Datas ORDER BY ID DESC";
    $result = mysqli_query($connect, $sql);
    ....
    ....
    ....
        $output .= '</table>';
        $fileName = "DB".date('Y_m_d').".xls";
        header("Content-Type: application/xls");
        header("Content-Disposition: attachment; filename=$fileName");
        echo $output;

        $zip = new ZipArchive;
        $tmp_file = 'myzip.zip';
        if ($zip->open($tmp_file,  ZipArchive::CREATE)) {
        $zip->setPassword>addFile('PASSWORD', $fileName); 
        $zip->setEncryptionName($fileName, ZipArchive: header('Content-disposition:EM_AES_256 attachment; filename=files.zip'); 
        header('Content-type: application/zip');
        $zip->close();
        readfile($tmp_file);

    }
}

  • The header type is probably incorrect and you don't actually output the zip file, https://stackoverflow.com/a/12226067/1213708. – Nigel Ren Jun 11 '20 at 09:56
  • @NigelRen I have followed the link and updated the code. The zip gets generated but unfortunately the zip is invalid. I am assuming the file never gets added. What is the mistake I am doing here? –  Jun 11 '20 at 10:23
  • 1
    Rather than `echo` the content of the spreadsheet, this will probably need to be written to the file (`file_put_contents($fileName, $output);`) so then add this file to the zip file. – Nigel Ren Jun 11 '20 at 10:34
  • @NigelRen Got it! Thank you :) –  Jun 11 '20 at 10:44

1 Answers1

1

I got it. If anyone needs it, the logic was to add contents of the database in excel and then output it.


       $output .= '</table>';
        $fileName = "DB".date('Y_m_d').".xls";
        header("Content-Type: application/xls");
        header("Content-Disposition: attachment; filename=$fileName");
        //echo $output;
        file_put_contents($fileName, $output);


    }

}

$zip = new ZipArchive;
$tmp_file = 'myzip.zip';
if ($zip->open($tmp_file,  ZipArchive::OVERWRITE|ZipArchive::CREATE)) {
    $zip->setPassword('PASSWORD');
    $zip->addFile($fileName);
    $zip->setEncryptionName($fileName, ZipArchive::EM_AES_256);
    header('Content-disposition: attachment; filename=files.zip');
    header('Content-type: application/zip');

    readfile($tmp_file);
}