PHP以0字节下载

时间:2012-10-08 16:10:46

标签: php download

我在一个目录中有ZIP文件,该目录距离根目录一步(防止链接等...)。这是代码:

<?php
    $filename = $_GET['id'];
    if(!$filename){
        header("Location: index.html");
    } else {
      function send_download($filename){
        $file_path = '../../../../downloads/' . $filename . '.zip';
        $file_size=@filesize($file_path);
        header("Content-Type: application/x-zip-compressed");
        header("Content-disposition: attachment; filename=$filename");
        header("Content-Length: $file_size");
        readfile($file_path);
        exit;
    } 
    send_download($filename);
    }
    ?> 

所有ZIP文件都可以,但在'a'标签上使用此方法会导致下载文件大小为0字节! :(

关于为什么的任何想法?

非常感谢!

5 个答案:

答案 0 :(得分:0)

您可以尝试将Content-type更改为以下内容:

Content-type: application/x-zip;

在此之前,请检查文件是否存在。

<?php
    $filename = $_GET['id'];
    if(!$filename){
        header("Location: index.html");
    } else{
    function send_download($filename){
    $file_path = '../../../../downloads/' . $filename . '.zip';
    if (file_exists($file_path))
    {
    $file_size=@filesize($file_path);
    header("Content-Type: application/x-zip-compressed");
    header("Content-disposition: attachment; filename=$filename");
    header("Content-Length: $file_size");
    readfile($file_path);
    exit;
    } 
    send_download($filename);
    }
    else
    die("Error 404!");
    }
?>

答案 1 :(得分:0)

  1. 标题(“位置:http://www.fqdn.tld/file.ext”);

  2. 基于_GET [“id”]为&gt; 0并且不为null,您创建了一个之后直接使用的函数,因此您只需添加更多行代码而无需任何用途。

  3. 我发现你添加了一个“@”符号,正如人们之前所评论的那样,但是,开始修复此问题的唯一方法是:

    • 删除@符号,因为你永远不应该使用它,非常糟糕的做法,你应该迎合你代码中的所有异常,这使得一个非常优秀的程序员。 (用PHP编写脚本)

    • 的error_reporting(E_ALL);

    • 将点b)放在它自己的行上,但在&lt;?php之后 - 所以我们可以看到完整的错误列表。

  4. 您的代码很好,您遇到的问题是权限,确保apache可以访问您的“文件”存储库,您可以检查该文件是否存在建议轻微权限且文件存在的事实,返回0字节表明在Apache级别拒绝读取权限。

答案 2 :(得分:0)

对,经过一段谷歌搜索和一些血,汗和泪,我终于找到了解决方案!

<?php 
    $filename = $_GET['id'];
    header('Content-type: application/zip'); 
    header("Content-Disposition: attachment; filename=" . $filename); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    readfile('../../downloads/' . $filename . ".zip"); 
    exit;  
?>

非常感谢所有人对此有所了解!

答案 3 :(得分:0)

以下是带有filesize的代码:

<?php 
    $filename = $_GET['id'];
    $file = "../../downloads/" . $filename . ".zip";
    header('Content-type: application/zip'); 
    header("Content-Disposition: attachment; filename=" . $file); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Content-length: " . filesize($file));
    readfile($file); 
    //echo filesize($file);
    exit;  
?>

答案 4 :(得分:0)

下面我们都在检查只有一个错误。

  

的ReadFile($文件); // $ file应该是相对的而不是绝对的。那就是它。

谢谢,

Anirudh Sood。