繁体   English   中英

Php force Download - 下载损坏的文件

[英]Php force Download - downloading corrupted file

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

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
$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 代码编写名称并下载每个文件。 并在文件名中使用../ ,甚至是您的文档或系统文件等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM