Home  >  Article  >  Backend Development  >  通过PHP实现浏览器点击下载TXT文档(转)_PHP教程

通过PHP实现浏览器点击下载TXT文档(转)_PHP教程

WBOY
WBOYOriginal
2016-07-20 11:13:58969browse

由于现在的浏览器已经可以识别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文件的下载。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440324.htmlTechArticle由于现在的浏览器已经可以识别txt文档格式,如果只给txt文档做一个文字链接的话,点击后只是打开一个新窗口显示txt文件的内容,并不能...
Statement:
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