Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/238.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 正在从服务器下载zip文件,导致意外结果。_Php_Zip_Readfile - Fatal编程技术网

Php 正在从服务器下载zip文件,导致意外结果。

Php 正在从服务器下载zip文件,导致意外结果。,php,zip,readfile,Php,Zip,Readfile,我的服务器上有一个zip文件,我有一些代码可以下载,但是当我打开它时,它是空的,但是当我直接从服务器上取下它时,文件大小仍然相同 我已确保所有php标记在打开/关闭之前或之后都没有空格,并尝试了在整个站点中找到的许多不同的解决方案,但没有一个有效。我还仔细检查了一下,以确保zip在服务器端也没有损坏 public function adownload() { $file = "template.zip"; if (file_exists($file)) {

我的服务器上有一个zip文件,我有一些代码可以下载,但是当我打开它时,它是空的,但是当我直接从服务器上取下它时,文件大小仍然相同

我已确保所有php标记在打开/关闭之前或之后都没有空格,并尝试了在整个站点中找到的许多不同的解决方案,但没有一个有效。我还仔细检查了一下,以确保zip在服务器端也没有损坏

    public function adownload()
{

    $file = "template.zip";
    if (file_exists($file)) 
    {
         header('Content-Description: File Transfer');
         header('Content-Type: application/zip');
         header('Content-Disposition: attachment; filename="'.basename($file).'"');
         header('Expires: 0');
         header('Cache-Control: must-revalidate');
         header('Pragma: public');
         header('Content-Length: ' . filesize($file));
         readfile($file);

    }
}

感谢您的建议。

我找到了一个很好的小指南,介绍了所有可能引发错误的事情,在我的例子中,我的类有ending?>标记。移除后,一切都很好。

在下载完成之前,您的浏览器正在关闭连接。这将导致存档zip目录为空

原因是服务器在高负载下阻塞

解决方案是通过将流分成更小的块来调整服务器的速度。使用以下代码代替
readfile()

set_time_limit(0); //prevent server timeout
$chunk_size = 1024 * 8; //set the chunk size to 8kB
$handle = fopen($file, 'rb');
$buffer = '';
while (!feof($handle)) {
     $buffer = fread($handle, $chunk_size);
     echo $buffer;
     flush();
     ob_flush();
     sleep(1); // take a break
}
fclose($handle);