首页 > 解决方案 > PHP - 解密后,如何从浏览器为用户提供打开/保存文件选项,而无需先保存文件?

问题描述

所以我有一个小测试应用程序,用户可以在其中上传文件(docx、png、jpg 和其他一些文件)。该文件被加密并保存到一个文件夹中。使用用户的 UID 和文件名创建一个 DB 表条目,例如

AA1234   Image100.jpg
BB2345   WorkDoc.Doc

这工作得很好,文件被加密并保存,表格包含信息。

要下载保存的加密文件,用户可以从适用于他们的文件列表中选择/选项(例如,我的 Image100.jpg,AA1234)。提交时,该工具应加载文件、解密并打开窗口以允许用户打开/保存文件

我的问题是,虽然这有效,但它不像我想要的那样整洁。代码加载文件,对其进行解密,将其保存为解密的临时文件,然后根据以下临时保存的文件为用户提供 OPEN/SAVE 窗口。(然后它会删除这个临时的、解密的文件)。

include('./lib/key.php');

//Get the filename and prepend the folder where the encrypted files are saved
$file = ('encuploads/'.$_POST["fileToDownload"]);

//Read the file and convert it to a string variable
$DocumentString = file_get_contents($file);

//Decrypt the file
$decryption=openssl_decrypt ($DocumentString, $ciphering, $key, $options, $iv); 

//Create a new temporary file containing the decrypted info
$decrypt = 'decrypted'.basename($_POST["fileToDownload"]);
$downloadfile = 'encuploads/'.$decrypt;
file_put_contents($downloadfile, $decryption);

//change the headers to output to a "download/save" window for the user
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"" . ($_POST["fileToDownload"]) . "\";");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($downloadfile));
ob_clean();
flush();
readfile($downloadfile); //showing the path to the server where the file is to be download

//delete the temporary file.
unlink(realpath($downloadfile))

因此,与其保存临时解密文件 -"file_put_contents($downloadfile, $decryption);"然后使用标头集读取它,"readfile($downloadfile);"我希望可以选择在标头语句之后直接使用 $decryption 变量

例如echo $decryption设置标题,以便为用户提供相同的 OPEN/SAVE 选项(对于选择的文件类型)

知道这是否是一个有效的选项或任何其他在解密后为用户提供下载选项的整洁方式(我不想要一个<a href="decryptedfilehere">DOWNLOAD</a>选项......我想要弹出窗口)

谢谢

标签: phphtmlformsfileencryption

解决方案


推荐阅读