有时需要一些文件不能在线打开,而是执行后需要下载,这时就用这个函数就可以解决了
代码如下:
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文件的下载。
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks agoByDDD
R.E.P.O. Save File Location: Where Is It & How to Protect It?
4 weeks agoByDDD

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version
