我已经在我的网站上运行此测试已有几天了,但它仍然使我感到困惑。
我的服务器上有一个zip文件。压缩文件中是一个单独的文本文件,其中包含短语“这是测试”。
在我的文件api.php中,我具有以下代码:
<?php
$originalFileName = "test.zip";
header("content-encoding: none");
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"" . "test.zip" . "\"");
header("Content-Length: " . filesize($originalFileName));
readfile($originalFileName);
?>
当我在firefox中访问api.php文件时。它提示下载文件大小为128字节的“ test.zip”。
当我单击“保存”时。它会在我的桌面上创建文件,但该文件的大小为0个字节,为空。
如果我使用直接IP地址即http://192.0.0.1/api.php
访问该网址,它将下载zip文件,并包含其预期的文本文件。
该域处于cloudflare下,并且禁用了缓存并且启用了开发人员模式,因此应该没有什么不同。
我使用了firefox的开发工具来复制域请求和ip请求的响应
域名请求-这将使0字节的空zip文件
HTTP/1.1 200 OK
Date: Sat, 01 Jun 2019 10:15:22 GMT
content-disposition: attachment; filename="test.zip"
Content-Length: 128
Content-Type: application/zip
content-encoding: none
Connection: keep-alive
X-Powered-By: PHP/7.2.16
Vary: User-Agent
Alt-Svc: h2=":443"; ma=60
CF-RAY: 4e006d0d4e615629-ORD
Server: cloudflare
UEsDBBQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAdGVzdC50eHR0aGlzIGlzIGEgdGVzdFBLAQIUABQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAAAAAAAEAIAAAAAAAAAB0ZXN0LnR4dFBLBQYAAAAAAQABADYAAAA0AAAAAAA=
直接IP请求-这将生成128字节的zip文件
HTTP/1.1 200 OK
Date: Sat, 01 Jun 2019 10:15:57 GMT
content-disposition: attachment; filename="test.zip"
content-length: 128
Content-Type: application/zip
content-encoding: none
Connection: Upgrade, Keep-Alive
X-Powered-By: PHP/7.2.16
Upgrade: h2,h2c
Vary: User-Agent
Keep-Alive: timeout=5
Server: Apache
UEsDBBQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAdGVzdC50eHR0aGlzIGlzIGEgdGVzdFBLAQIUABQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAAAAAAAEAIAAAAAAAAAB0ZXN0LnR4dFBLBQYAAAAAAQABADYAAAA0AAAAAAA=
除了响应头中的一些细微变化外,响应负载都是相同的。
例如字母大写和cloudflare标头。
在尝试通过域保存下载提示时,我看不出zip文件应为0字节的任何原因。
当我按ctrl + j查看下载历史记录时。 底部的直接ip下载看起来不错,顶部的一个域名看起来很奇怪。
有人对如何解决这个问题有任何建议吗?
答案 0 :(得分:0)
I tested your issue, maybe changing some headers
this may solve the question, with my headers
I can see the zip
file downloaded and opening it's fine... let's me know if with my code
your question is solved...
<?php
$file = basename("test.zip");
$downloads_folder = "./";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($downloads_folder . $file)));
// Open and output file contents
set_time_limit(0);
$fh = fopen($downloads_folder . $file, "rb");
while (!feof($fh)) {
echo fgets($fh);
ob_flush();
flush();
}
fclose($fh);
exit;
?>
I hope this helps.