php强制下载类型的实现代码 |
本文标签:强制下载 复制代码 代码如下: 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文件的下载 。 |