首页 > 解决方案 > 如何在 php 中的 zip 文件中使用 excel 密码保护

问题描述

我想在 zip 文件夹中下载 excel。之后,它应该受到密码保护。但它不起作用。

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

}

标签: phpcodeigniterphpexcel

解决方案


由于PHP >7.2,您可以使用setEncryptionName来处理带有密码的 ZIP 存档。

 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';
}

在使用密码保护 ZIP 存档中查看更多信息


推荐阅读