1

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

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);
    }

我可以通过以下方式获取与产品关联的文件名

$演示

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

4

1 回答 1

6
<?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 代码编写名称并下载每个文件。并带有../文件名,甚至是您的文档或系统文件等。

于 2014-04-21T08:22:09.317 回答