无法在PHP中下载二进制文件 [英] Unable to download binary file in PHP
问题描述
我必须加密一个文件,并将其作为Blob保存在mysql中,然后解密并使其可供下载. 我将文件保存在这样的Blob中:
I have to encrypt a file and save it in mysql as a blob, then decrypt it and make it available for download. I save the file in a blob like so:
$certificate_tmp=$_FILES['certificate']['tmp_name'];
$certificate=openssl_encrypt(file_get_contents($certificate_tmp),$ciphers,$password_tmp);
$wpdb->insert("my_table",array("certificate"=>$certificate));
注意:我已经剪切了不相关的代码,该表不仅是证书,而且我不希望这引起混淆.
Note: I've cut unrelated code, the table is not just certificate, but I don't want this to get confusing.
这是下载php页面:
$password_tmp=$_SESSION['pwd']; //decrypt password
global $wpdb; //wordpress db conncetion
$results_file = $wpdb->get_row("select * from my_table where id='$id'",ARRAY_A); //i get the id from wp's curr_user
$m_file = openssl_decrypt($results_file['certificate'],"AES-128-CBC",$password_tmp);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\certificate".$id."\"");
header('Content-Transfer-Encoding: binary');
print_r($m_file);
所有操作都与文本文件完美配合,但是对于二进制文件,结果为空,尽管二进制文件中存在二进制文件.
And everything works perfectly with text files, but the result is empty with binary files, although in the blob the binary file is there.
编辑
我的猜测是,一旦我从db blob解密文件,php或html(由于print_r
)就知道它是一个二进制文件,并且出于安全原因不允许您显示它.尽管我上传的文件(二进制文件或文本文件)都没有扩展名,但您无法在网络上执行 .exe或.bin 之类的程序.
据我了解,php将二进制文件视为字符串,但是file_get_contents
是二进制安全的.
我认为不使用Blob将是最好的方法,但是我不能这样做,我必须使用Blob.
EDIT
My guess is, as soon as I decrypt the file from the db blob, php or html (because of print_r
) understands that it is a binary file and doesn't let you show it because of security reasons. You can't execute programs on the web like .exe or .bin, although the files I upload, either binary or text have no extension.
From what I understand php treats binary files as strings, but file_get_contents
is binary safe.
I think not using blobs would be the best approach for this, but I cannot do that, I have to use blobs.
编辑2 问题似乎是 openssl 似乎没有为了喜欢二进制数据,我尝试使用 mcrypt 进行相同的代码完美地工作.
EDIT 2 The problem seems to be openssl which doesn't seem to like binary data, I've tried the same code using mcrypt and it works perfectly.
推荐答案
- 确保您使用相同的密钥解密数据.
-
为什么使用
print
代替print_r
?
尝试添加内容长度:
header('Content-Length:'.strlen(YourFileData));
header('Content-Length: '.strlen(YourFileData));
有关更多信息,请访问: http://www.media -division.com/the-right-way-to-handle-file-downloads-in-php/
For more information please visit: http://www.media-division.com/the-right-way-to-handle-file-downloads-in-php/
这篇关于无法在PHP中下载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!