php中的强制文件下载
我建立了一个简单的文件管理器,用户可以下载任何类型的文件,如pdf、word或gif文件。我希望他们都下载文件,而不是在浏览器中查看。上传的文件名存储在数据库中 您可以使用“内容处置”标题:php中的强制文件下载,php,Php,我建立了一个简单的文件管理器,用户可以下载任何类型的文件,如pdf、word或gif文件。我希望他们都下载文件,而不是在浏览器中查看。上传的文件名存储在数据库中 您可以使用“内容处置”标题: header("Content-Disposition: attachment"); 提供了一个很好的例子。通常在发送文件之前将内容配置设置为附件,通过浏览器强制下载 您需要配置web服务器为文件提供此标头,或者自己通过PHP发送文件,在发送之前发送特定标头,如: header('Content-Disp
header("Content-Disposition: attachment");
提供了一个很好的例子。通常在发送文件之前将
内容配置设置为附件
,通过浏览器强制下载
您需要配置web服务器为文件提供此标头,或者自己通过PHP发送文件,在发送之前发送特定标头,如:
header('Content-Disposition: attachment; filename=your_file_name.pdf');
请注意,第一种解决方案更好,因为脚本运行时间太长(您也可以更改它),因此您不会冒下载被切断的风险。源代码取自库
无论如何,最重要的部分是
header('Content-Disposition: attachment; filename="'.basename($name).'";');
注意最后的代码>在字符串中,没有它,它将无法工作此网站上已多次询问此文件的可能副本。我要求多格式下载,而不仅仅是pdf。我希望客户端也能下载word、excel、gif。如果你想避免缓存,最好使用Cache控件:no Cache
标题。那些换行符(\n
)和代码>不是必需的。
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/pdf;\n");
$len = filesize($filename);
header("Content-Length: $len;\n");
header("Content-Disposition: attachment; filename=\"downfile.pdf\";\n\n");
echo readfile($filename)
// download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');
}
header('Content-Description: File Transfer');
if (headers_sent()) {
$this->Error('Some data has already been output to browser, can\'t send PDF file');
}
header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
// force download dialog
if (strpos(php_sapi_name(), 'cgi') === false) {
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream', false);
header('Content-Type: application/download', false);
header('Content-Type: application/pdf', false);
} else {
header('Content-Type: application/pdf');
}
// use the Content-Disposition header to supply a recommended filename
header('Content-Disposition: attachment; filename="'.basename($name).'";');
header('Content-Transfer-Encoding: binary');
$this->sendOutputData($this->getBuffer(), $this->bufferlen);
break;
header('Content-Disposition: attachment; filename="'.basename($name).'";');