PHP强制下载文件-要么下载中断,要么系统显示文件无效/损坏


PHP force download of file - either getting download interruped or system says invalid/corrupt file

我试图实现的是通过PHP强制下载文件。我面临着两个问题,一想到这里可能出了什么问题,我就崩溃了。

  1. 每当我尝试使用IE下载文件时,下载大约在中途中断,即说我的文件大小为1024Kb,大约500Kb是下载停止时,因为我在IE中收到一条错误消息,说"下载中断"
  2. 我经常(但并不总是)遇到的另一个问题是,下载的文件(实际上是一个zip文件)有时会因为某种原因而损坏!服务器上的文件还可以——如果我直接从那里下载,一点问题都没有。然而,如果我使用PHP脚本下载,然后尝试解压缩文件,Windows会说"无效或损坏的文件…"

我真的需要一些帮助。

以下是下载文件的代码块:-

$fileName = "./SomeDir/Somefile.zip";
$fsize = filesize($fileName); 
set_time_limit(0);
// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-type: application/zip');
header("Content-Disposition: attachment; filename='"".basename($fileName)."'";");
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header("Content-Length: " . $fsize);
// download
$file = @fopen($fileName,"rb");
if ($file) {
  while(!feof($file)) {
print(fread($file, 1024*8));
flush();
if (connection_status()!=0) {
  @fclose($file);
  die();
}
}
@fclose($file);
}

试试这个

<?php
$file = "./SomeDir/Somefile.zip";
set_time_limit(0);
$name = "Somefile.zip";
// Print headers and print to output.
header('Cache-Control:');
header('Pragma:');
header("Content-type: application/zip");
header("Content-Length: ". filesize($file));
header("Content-Disposition: attachment; filename='"{$name}'"");
readfile($file);
?>

我认为您的内容长度报告的字节数超过了实际传输的字节数。请检查服务器的日志。服务器可以对内容进行gzip,当它关闭连接时,客户端仍在等待剩余的声明字节。