简体   繁体   中英

How to excel password protected in zip file in php

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);

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM