【问题标题】:Php force Download - downloading corrupted filephp force 下载 - 下载损坏的文件
【发布时间】:2014-06-05 05:44:51
【问题描述】:

您好,我正在尝试允许下载与产品相关的演示文件。我的代码是这样的

if(isset($_POST['submit'])){     
    $root = $_SERVER['DOCUMENT_ROOT'];
    $path = "/download/";
    $path = $root.$path;
$filename = $demo;
$file = $path.$filename;
header('Content-Type: application/force-download');
header("Content-Transfer-Encoding: Binary"); 
header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
header("Content-Length: ".filesize($file));
 readfile($file);
    }

我可以通过

获取与产品相关联的文件名

$演示

用户提交信息后,下载将自动开始。现在这是用正确的文件名下载不存在的文件或损坏的文件。请帮忙

【问题讨论】:

    标签: php force-download


    【解决方案1】:
    <?php
    $file = 'monkey.gif';
    
    if (file_exists($file)) {
        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;
    }
    
    ?>
    

    如您所见,内容类型为application/octet-steam,表示文件是逐字节编码的。还设置了缓存标头。然后标题由ob_clean();flush() 强制发送;然后读取文件。

    file_exists 用于确保给定文件存在。您还应该尽量不要强行用户输入,因为他们可以轻松地为您的 php 代码编写名称并下载每个文件。在文件名中加上../,甚至是您的文档或系统文件等等。

    【讨论】:

    • 帮助很大! @Seti。这行得通。感谢您的详细回答。
    猜你喜欢
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 2012-12-05
    • 1970-01-01
    相关资源
    最近更新 更多