PHP 下载量为 0 字节

问题描述 投票:0回答:6

我的 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 字节! :(

有什么想法吗?

非常感谢!

php download
6个回答
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!");
    }
?>

0
投票
  1. header("位置:http://www.fqdn.tld/file.ext");

  2. 基于 _GET["id"] > 0 并且不为 null,您创建了一个随后直接使用的函数,因此您只是添加了更多行代码,但没有任何必要的目的。

  3. 我看到您添加了“@”符号,正如人们之前评论的那样,但是,您开始解决此问题的唯一方法是:

    • 删除@符号,因为你永远不应该使用它,这是非常糟糕的做法,你应该照顾代码中的所有异常,这才能成为一个真正优秀的程序员。 (PHP 脚本)

    • 错误报告(E_ALL);

    • 将点 b) 放在它自己的线上,但位于

    • 之后
  4. 你的代码很好,你遇到的问题是权限,确保apache可以访问你的“文件”存储库,事实上你能够检查文件是否存在,这表明有轻微的权限并且文件存在,这一点是0返回字节表明读取权限在 Apache 级别被拒绝。


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;  
?>

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


0
投票

这是带有文件大小的代码:

<?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;  
?>

0
投票

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

readfile($file); //$file 应该是相对的而不是绝对的。就是这样。

谢谢,

阿尼鲁德·苏德。


0
投票

我知道这是一个非常老的问题,尽管我刚刚为自己解决了这个问题。就我而言,它是 Content-Length 标头,我有:

header ('Content-Length: "'.$fileSize.'"');

更改为:

header ('Content-Length: '.$fileSize);

为我解决了这个问题,PHP 试图解释 " 但只用整数就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.