Home  >  Article  >  php教程  >  php强制下载文件

php强制下载文件

WBOY
WBOYOriginal
2016-06-13 10:33:55841browse

由于现在的浏览器已经可以识别格式为txt的文档格式,所以如果只是给txt文档做一个文字链接的话,可能只是打开一个新窗口显示txt文件的内容,并不能实现点击下载的目的。We have to do something else.
当然这个问题的解决办法也可以是你将你的txt文件改名为浏览器不认识的文件,比如rar,这样的话点击,浏览器不认识就只好让用户下载了。

下面这个文件就是通过设置header设置文档的格式来实现点击下载的目的,将上个页面传递过来的文件点击可以下载。

$filename = "/somepath/".$_GET[file].".txt";   //要下载的文件名
 
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=".basename($filename));
readfile($filename);
 
?>

首先:设置Content-Type的值为application/force-download,强制下载

接着第二个header函数设置了要下载的文件,注意这里filename是不包含路径的文件名,所以用basename过滤掉路径名。这个filename的值将来就是点击下载后弹出对话框里面的文件名.

最后就是readfile,将文件流输出到浏览器,这样就实现了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