用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文件的下载。

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

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Solution to Redirecting 404 Errors after Simulation Login When using Selenium for Simulation Login, we often encounter some difficult problems. �...

How to implement cross-application jump for Word plug-in login authorization? When using certain Word plugins, we often encounter this scenario: click on the login in the plugin...

Use Python's subprocess module to execute wmic...

Discussion on the task status after the local computer of Jiutian Computing Power Platform is closed. Many users will encounter a question when using Jiutian Computing Power Platform for artificial intelligence training...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

How to achieve login authorization from within the application to outside the application? In some applications, we often encounter the need to jump from one application to another...
