PHP 强制标头下载不适用于 zip 文件


PHP force header download not working on zip files

我有一个文档下载站点,我可以在其中跟踪下载的文件。

我的问题是通过我正在使用的脚本下载 zip 文件。除了zip文件之外,所有其他文件都会被迫下载。当一个zip文件被推送时,它只是进入下载.php页面,其中脚本没有被推送出来。

          ob_start();
    header('Content-Description: File Transfer');
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename='.basename($file));
          header('Content-Transfer-Encoding: binary');
          header('Expires: 0');
          header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
          header('Pragma: public');
          header('Content-Length: ' . filesize($file));
    ob_clean();
          flush();
          readfile($file);
          exit;

这是一个对我有用的代码片段:

if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
    header('Content-Type: "application/octet-stream"');
    header('Content-Disposition: attachment; filename="'.basename($file_url).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header("Content-Transfer-Encoding: binary");
    header('Pragma: public');
    header("Content-Length: ".filesize($file_url));
} else {
    header('Content-Type: "application/octet-stream"');
    header('Content-Disposition: attachment; filename="'.basename($file_url).'"');
    header("Content-Transfer-Encoding: binary");
    header('Expires: 0');
    header('Pragma: no-cache');
    header("Content-Length: ".filesize($file_url));
}
readfile($file_url);

有类似的问题,这句话对当时有所帮助:

header('Content-Disposition: attachment; filename="'.basename($file).'"');

我没有使用内容处置和长度的base_name,而是使用了完整路径。使用base_name对我有用。

相关文章: