php - 如何在 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);
}
解决方案
由于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 存档中查看更多信息
推荐阅读
- c++ - 有没有合法的方法将 unsigned char 指针转换为 std::byte 指针?
- javascript - 附加的 ajax 请求中断其他已经附加的 ajax 请求(纯 js)
- firebase - React-native ListView 排序数据
- python - 无法在 PyCharm 中键入字母或数字
- windows - 如何在 python Popen 中命名子进程?
- .net - 使用更改密钥反序列化 JSON?
- css - 不活动时禁用覆盖链接(移动设备)
- javascript - three.js - rotate a rectangular sprite around a sphere maintaining minimum proximity
- css - 一侧圆形的 CSS 按钮
- c# - WPF MVVM C#:列表框拖放,无需代码