【问题标题】:PHP is reading file instead of downloadingPHP正在读取文件而不是下载
【发布时间】:2012-04-17 05:51:16
【问题描述】:

我有下面的脚本,用于使用 PHP 从文件夹下载文件,它在本地工作,但在线它正在下载页面上读取和打印。

if( $result && count($result) > 0){
    $row = $result[0];
    $book = true;
    $Location = './files/';
    $bookLocation = $Location . $row['file_name']; // exampe: report.zip
    if( file_exists( $bookLocation ) ){
        $fileLocation = $bookLocation;
        $file_size = filesize($fileLocation);
        echo 'Please wait downloading the file....';
        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Disposition: attachment; filename=' . $row['file_name']);
        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: ' . $file_size);
        ob_clean();
        flush();
        readfile($fileLocation);
        exit;      
    }else{
        echo '<h3>Sorry!, file not found...</h3>';
    }
}

.htaccess 脚本

RewriteEngine on

RewriteRule ^$ index.html
RewriteRule ^index.html$ index.php

RewriteRule ^([0-9]{1,9})(/)([^/\.]+[^/\.]+)(_+[^/\.]+)(\.html|)/?$ index.php?id=$1&cat=$3
RewriteRule ^([^/\.]+[^/\.]+)(\.html|)/?$ index.php?page=$1
RewriteRule ^(.*)(/)([0-9]{1,9})(/)(.*)(\.html|)/?$ index.php?view_file=$3&file=$5
RewriteRule ^(.*)(/)([0-9]{1,9})(/)(.*)(\.htm)/?$ index.php?download=$3

RewriteRule ^(author)(/)(.*)(.html)/?$ index.php?user=$1

感谢您的帮助。

【问题讨论】:

  • 在本地你不是从浏览器运行它吗?
  • 尝试创建一个带有链接的新文件..链接将指向该文件....然后尝试执行新页面并点击链接!!
  • 服务器最终会修改header吗?
  • 嗨@Core,如果您对此问题有任何答案,请编辑您的答案:)

标签: php .htaccess


【解决方案1】:

正如 Christian 所建议的,您必须删除代码中的 echo 语句。如果即使在那之后它仍然不适合您,请尝试更换该行

header('Content-Type: application/force-download');

header('Content-Type: application/octet-stream');

【讨论】:

    【解决方案2】:

    在某些浏览器中,您可能将其设置为自动下载并运行该特定文件类型。

    如果是这样,就没有办法“解决”这个问题。浏览器决定如何处理文件,即使你告诉它下载它,用户也可能告诉它直接运行。

    大编辑

    虽然我之前的评论是正确的,但您的代码中有一个主要问题:

        $file_size = filesize($fileLocation);
        echo 'Please wait downloading the file....';
        header('Content-Description: File Transfer');
    

    必须删除 echo 声明。它必然会导致问题,例如未发送标头。考虑到您的描述,我会说这是您的问题。

    请注意,一旦您发送任何内容,您就无法发送更多标头。

    【讨论】:

    • 嗯,它应该可以工作如果早一点有ob_start(),对吧?
    • 那个 echo 可能是问题所在,而不是其他问题,因为他使用二进制作为内容类型。
    • @bububaba 正确,但我在任何地方都没有看到ob_start()
    猜你喜欢
    • 2013-07-02
    • 2021-12-13
    • 2019-07-21
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    相关资源
    最近更新 更多