1

I want to download excel in zip folder. After that, it should be password protected. But it does not work.

public function download (){

    $header = array('id');

    require_once APPPATH."/third_party/PHPExcel.php";
    $sheet = new PHPExcel();
    $file = $this->appmodel->Data();
    // echo "<pre>"; print_r($file); die;
    $filename = $file->id;
    $this->load->helper('date');
    $date = date('Y-m-d'); 
    //1st Sheet
    $sheet->setActiveSheetIndex(0);
    $activeSheet = $sheet->getActiveSheet();
    $activeSheet->fromArray($header, null);

    $objWriter = PHPExcel_IOFactory::createWriter($sheet, 'Excel2007');  
    // echo "<pre>"; print_r($objWriter); die;
    $excel_file_tmp = tempnam("/tmp", 'your_prefix');
    $objWriter->save($excel_file_tmp);

    //zip
    $zip_file_tmp = tempnam("/tmp", 'your_prefix');
    $zip        = new ZipArchive();
    $zip->open($zip_file_tmp, ZipArchive::OVERWRITE);
    $zip->addFile($excel_file_tmp, 'your_name.xlsx');
    $zip->close();

    //download
    $password = "22";
    $download_filename = 'your_name.zip'; 
    header("Content-Type: application/octet-stream");
    header("Content-Length: " . filesize($zip_file_tmp));
    header("Content-Disposition: attachment; filename=\"" . $download_filename . "\"");
    @system("zip -P $password $excel_file_tmp $zip_file_tmp ");
    readfile($zip_file_tmp);
    // unlink($excel_file_tmp);
    // unlink($zip_file_tmp);
    @unlink($zip_file_tmp);

}
barbsan
  • 3,418
  • 11
  • 21
  • 28
Puneet
  • 11
  • 3
  • 1
    ZipAchive does have a `setPassword` method, y'know? Any why would you set the headers from a file, and then stream a changed one? That's probably not helping. – Jonnix May 22 '19 at 08:11
  • Please explain what does mean *not work* - it's just not protected or do you get some error? – barbsan May 22 '19 at 08:35
  • zip folder download but not protected – Puneet May 22 '19 at 09:11
  • Actually I want excel sheet password protected but it's not work so I create zip to password protected – Puneet May 22 '19 at 09:12

1 Answers1

0

Since PHP >7.2 you can use setEncryptionName to procted a ZIP archive with a password.

 if ($res === TRUE) {
   $zip->addFromString('FILENAME_WITH_EXTENSION', 'file content goes here'); //Add your file name
   $zip->setEncryptionName('FILENAME_WITH_EXTENSION', ZipArchive::EM_AES_256, 'PASSWORD'); //Add file name and password dynamically
   $zip->close();
   echo 'ok';
} else {
   echo 'failed';
}

See more at Protect ZIP Archive with password

Dylan KAS
  • 4,840
  • 2
  • 15
  • 33