下载.zip文件运行损坏的文件php

时间:2010-01-18 18:30:06

标签: php header download zip

我正在尝试强制下载受保护的zip文件(我不希望人们在没有先登录的情况下访问它。

我有为login等创建的函数,但我遇到了下载文件损坏的问题。

这是我的代码:

$file='../downloads/'.$filename;
header("Content-type: application/zip;\n");
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($file).";\n");
header("Content-disposition: attachment; filename=\"".basename($file)."\"");
readfile("$file");
exit();

这是错误:Cannot open file: It does not appear to be a valid archive.

否则文件下载会很好,所以它一定是标题我做错了。

有什么想法吗?

7 个答案:

答案 0 :(得分:26)

此问题可能有多种原因。可能您的文件未找到或无法读取,因此文件的内容只是PHP错误消息。或者已经发送了HTTP标头。或者你有一些额外的输出,然后破坏你的文件的内容。

尝试在脚本中添加一些错误处理,如下所示:

$file='../downloads/'.$filename;
if (headers_sent()) {
    echo 'HTTP header already sent';
} else {
    if (!is_file($file)) {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
        echo 'File not found';
    } else if (!is_readable($file)) {
        header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
        echo 'File not readable';
    } else {
        header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: ".filesize($file));
        header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
        readfile($file);
        exit;
    }
}

答案 1 :(得分:7)

我打赌两个啤酒发生了PHP错误,错误消息搞砸了ZIP文件。请求的文件可能不存在。

用记事本或类似的文本编辑器打开ZIP文件,找出问题所在。

答案 2 :(得分:1)

这是解决方案 创建一个名为.htaccess的文件 写下面的那行 SetEnv no-gzip不要改变

将文件上传到您的网站。如果您已经存在该文件,请在该

中进行上述更改

答案 3 :(得分:1)

迟到的答案,但对于无法使force download工作的用户可能会有用 在php脚本

的顶部添加以下内容
<?php
apache_setenv('no-gzip', 1);
ini_set('zlib.output_compression', 0);

答案 4 :(得分:0)

尝试此操作以查找是否有任何错误

error_reporting(0);

在编写标题之前不要打印任何内容; 在代码编辑标题之后运行脚本的ob_start(),然后运行ob_flush()和ob_clean()

答案 5 :(得分:0)

我对大型zip文件有类似的问题 这对我有用:

在您的php.ini中,更改为:

  • 最大上传文件大小-1500 M
  • 最大输入时间-1000
  • 内存限制-640M
  • 最长执行时间-1800
  • Post_max_size-2000 M

在您的php文件中。

    $filename = "MyFile.zip";           
    $filepath='../downloads/'.$filename;    //your folder file path    
    header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: Binary");    
    header("Content-Length: ".filesize($filepath)); 
    header("Content-Disposition:attachment;filename=\"".basename($filepath)."\"");


    while (ob_get_level()) 
    {
     ob_end_clean();
     }
    readfile($filepath);   
    exit;
    ob_start ();

答案 6 :(得分:0)

@Pekka赢得2杯啤酒! https://stackoverflow.com/a/2088288/9294174 在我的情况下,打开终端并使用nano读取文件向我显示了xdebug消息...

相关问题