嗨,我正在尝试允许下载一个与产品相关的演示文件。我的代码像这个
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
用户提交信息后,下载将自动开始。现在,这是下载一个不存在的文件或损坏的文件与正确的文件名。请帮助
<?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代码编写名称并下载EACH文件。并且在文件名中使用../
,甚至是您的文档或系统文件等等。