Home > php教程 > php手册 > body text

php强制下载类型的实现代码

WBOY
Release: 2016-06-06 20:36:37
Original
993 people have browsed it

有时需要一些文件不能在线打开,而是执行后需要下载,这时就用这个函数就可以解决了

代码如下:
function downloadFile($file){
/*Coded by Alessio Delmonti*/
$file_name = $file;
$mime = 'application/force-download';
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile($file_name); // push it out
exit();
}

php将文件下载下来而不是超链接下载,这样可以减少盗链的情况!将文件给浏览器让浏览器下载

以txt类型为例

由于现在的浏览器已经可以识别txt文档格式,如果只给txt文档做一个文字链接的话,点击后只是打开一个新窗口显示txt文件的内容,并不能实现点击下载的目的。当然这个问题的解决办法也可以是将txt文件改名为浏览器不认识的文件(比如rar),这样的话,由于浏览器不能识别rar类型的文件,只能让用户下载了。还有一种办法,就是利用代码通过header设置文档的格式来实现点击下载的目的。
PHP代码如下:
代码如下:
$filename = '/path/'.$_GET['file'].'.txt'; //文件路径
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=".basename($filename));
readfile($filename);

简要说明:
第一个header函数设置Content-Type的值为application/force-download;
第二个header函数设置要下载的文件。注意这里的filename是不包含路径的文件名,filename的值将来就是点击下载后弹出对话框里面的文件名,如果带路径的话,弹出对话框的文件名就是未知的;
最后通过readfile函数,将文件流输出到浏览器,这样就实现了txt文件的下载。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!