PHP通过header实现文本文件下载的代码
这就是今天讨论的主要问题。PHP帮助文档里面关于PHP通过header触发下载的说明比较简单,而网上关于此方面的文章也少的可怜,有很多文章都无法实现所需要的效果。今天我也来谈一下这个方面的话题,如果你感觉比网上的某些文章有所改进,那我就很知足了。
如果从准确的角度来说,那PHP文档是最准确的,因为它很简练的列出了实现文本类文件触发下载所需要的三条语句,以PDF为例就是:
复制代码 代码如下:
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
这三句是正确的,但是在真正用的过程中很容易出现一些无法预料的问题,如果你是一个很仔细的人的话,也可以很容易的避免这些问题。而我不是,所以我就遇到了这样的问题,这里就以我的问题来简单说一下。
对于第一句,应该没啥说的,是必须的,只要改一下文档的类型就行,例如是下载txt文件,那就改为header(‘Content-type: application/txt');,第二句也没啥说的,就是为你的下载文档起一个名字,如果是txt文件的话,可以改为header(‘Content-Disposition: attachment; filename=”downloaded.txt”‘);,第三句的问题就比较多了,readfile这个函数的意思就是读取一个文件然后输出,这里文件的路径需要是真实的文件路径,如果是downloads文件夹下面的一个original.txt文件,可以这样写readfile(‘downloads/original.txt');,而如果提交的页面会输出文本等字符,那么下载到的文件会是原文件original.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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
