简体   繁体   English

下载zip时php标头问题

[英]php header issue when downloading zip

I'm trying to make php download a .zip file using this code: 我正在尝试使用以下代码使php下载.zip文件:

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);

$file is right. $ file是正确的。

I have two problem with this script: 这个脚本有两个问题:

  1. If I use header('Content-Length: ' . filesize($file)); 如果我使用header('Content-Length: ' . filesize($file)); the download is corrupt with 0 bytes file. 0字节文件下载已损坏。 If I comment this line, the download looks good on ubuntu. 如果我对此行发表评论,那么在ubuntu上下载看起来不错。

  2. If I use mac OS to download this file, after opening the .zip it extracts .cpgz file (for what I read is when the zip is corrupt) 如果我使用Mac OS下载此文件,则在打开.zip文件后,它将解压缩.cpgz文件(因为我看到的是zip损坏时的内容)

I've tried all kind of headers to make this work, but the problem is always on that header. 我已经尝试过各种标头来实现此目的,但问题始终出在该标头上。 My question is: how can I make this work on all OS? 我的问题是:如何在所有操作系统上都可以使用此功能?

I use this for the purpose of downloading any kind of file using one generic PHP-script: 我将其用于使用一个通用PHP脚本下载任何类型的文件的目的:

$base = "/path/to/downloadable/files";
$file = "myArchive.zip"; // or anything else

if(file_exists($base.$file)){        
    header('Content-Description: Download');
    header('Content-Type: '.mime_content_type($base.$file));
    header('Content-Disposition: attachment; filename="'.basename($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('Content-Length: ' . filesize($base.$file));
    echo file_get_contents($base.$file);
}

This works fine for me with almost every kind of file (including .zip). 这对几乎所有类型的文件(包括.zip)都适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM