mck*_*k89 2 php header download tar
我在服务器上有一个tar存档,必须可以通过php下载.这是我用过的代码:
$content=file_get_contents($tar);
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=$tar");
header("Content-Length: ".strlen($content));
unlink($name);
die($content);
Run Code Online (Sandbox Code Playgroud)
该文件已下载,但已损坏,无法打开.我认为标题有问题,因为服务器上的文件可以打开而没有问题.你知道我怎么能解决这个问题?
更新 我试图像这样打印一个iframe:
<iframe src="<?php echo $tar?>"></iframe>
Run Code Online (Sandbox Code Playgroud)
下载工作正常,所以我确信标题中缺少一些内容.
小智 5
我不得不这样做时使用了这段代码:
function _Download($f_location, $f_name){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($f_location));
header('Content-Disposition: attachment; filename=' . basename($f_name));
readfile($f_location);
}
_Download("../directory/to/tar/raj.tar", "raj.tar");
//or
_Download("/var/www/vhost/domain.com/httpdocs/directory/to/tar/raj.tar", "raj.tar");
Run Code Online (Sandbox Code Playgroud)
试试吧.
不要使用file_get_contents()然后echo或print输出文件.这会将文件的全部内容加载到内存中.一个大文件可以/将超过你的脚本memory_limit并杀死脚本.
为了将文件的内容转储到客户端,最好使用readfile()它 - 它将正确地填充文件块并在客户端将它们吐出而不会超出可用内存.请记住在这之前关闭输出缓冲,否则你基本上只是再做file_get_contents()一次
所以,你最终得到这个:
$tar = 'somefile.tar';
$tar_path = '/the/full/path/to/where/the/file/is' . $tar;
$size = filesize($tar_path);
header("Content-Type: application/x-tar");
header("Content-Disposition: attachment; filename='".$tar."'");
header("Content-Length: $size");
header("Content-Transfer-Encoding: binary");
readfile($tar_path);
Run Code Online (Sandbox Code Playgroud)
如果您的tar文件实际上是gzip压缩文件,那么请改用"application/x-gtar".
如果文件在下载后仍然出现损坏,请在客户端进行一些检查: