如何解决通过php下载zip
我正在尝试通过 PHP 下载 zip 文件。文件名存储在数据库中,所有文件都存储在名为“products”的文件夹中。这是我正在使用的代码:
function downloadProduct($id,$connection){
$sql = "SELECT filename FROM productdata WHERE id = '$id'";
$query = MysqLi_query($connection,$sql);
if(MysqLi_num_rows($query) == 1){
$file = basename(MysqLi_fetch_assoc($query)["filename"]);
$filePath = "products/" . $file;
if(file_exists($filePath)){
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-transfer-encoding: binary");
readfile($filePath);
exit;
}
echo("<script>alert('This file (' + '$file' + ') does not exist.')</script>");
}
else{
echo("<script>alert('Can not download this file.')</script>");
}
}
文件路径总是正确的(当我提醒它时),但是当文件被读取时,它不会停止在我的页面底部显示这些字符:
.I*��9UZ��3�8s�A��u�sz]���~������x�����9&NU�""c$M��.�� ^��N���U�ַΣ�p�hc��K��b�>�Sզ�<��k��l��rofz
~���ۛ9�[��͜���֡�\�n�z�y��϶T�W�;� ᧔e ���{qO #m�/�#�L�=�a�_��e��l)5�e�q�&�#��g��s-������{L |i�[8�ZV�|v+�\��G���I�iDShS�g�n(7���� W���˛������T�k�p�K� ��/]�^��7��,Uwf�Z Ѽ�" U�� �L\T%���7M� 9�>ǩ_ �V��ᯇ.�iUι�a����F�K�ڦéc�9��䗗ki�KK�u��\�u�F䨪���b����� �3��q���ָ~�e\o����:G�U�q��K�� �V��
我也尝试了不同的标题,但没有任何改变。代码对我来说似乎是正确的。我希望有一个人可以帮助我。谢谢。
解决方法
这看起来像是标题问题。我将这些标头用于 ZIP 文件的输出:
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-disposition: attachment; filename='.$filename);
你可以试试看。是文件的扩展名使其成为 ZIP 文件,而不是 Content-Type
标头。
我不确定这会有所帮助。许多其他问题可能会导致您的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。