嗨,我正在尝试下载一个演示文件,这是相关的产品。我的代码是这样的
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);
}我能够获得与产品相关联的文件名
$demo
用户提交信息后,下载将自动启动。现在,这是下载一个不存在的文件或损坏的文件与正确的文件名。请帮帮忙
发布于 2014-04-21 08:22:09
<?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代码编写名称并下载每个文件。在文件名称中使用../,甚至您的文档或系统文件等等。
https://stackoverflow.com/questions/23192683
复制相似问题