PHP USES header to implement the text file download code

  • 2020-03-31 21:00:06
  • OfStack

That's the main question for today. The instructions in the PHP help documentation for PHP to trigger a download via a header are relatively simple, and there are few articles on this topic on the web, many of which fail to achieve the desired effect. I'm going to talk about that today, too, and if you feel better about it than some of the articles on the web, I'm happy.

The PHP document is the most accurate, in the sense that it simply lists the three statements needed to trigger the download of a text file. Take PDF for example:
 
// 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'); 

These three sentences are true, but it's easy to have unexpected problems in the process of using them, and it's easy to avoid them if you're a careful person. And I'm not, so I have this problem, and I'm going to talk about it briefly.

For the first sentence, there should be nothing to say, it is necessary, just change the type of the document, such as download TXT file, that is changed to header(' content-type: application/ TXT '); If it is a TXT file, you can change it to header(' content-attachment: attachment; Filename = "downloaded. TXT" "); The function readfile means to read a file and then output it. The path of the file here needs to be the real file path. If it's an original.txt file under the downloads folder, you can say readfile(' downloads/original.txt'); , and if the submitted page will output text and other characters, then the downloaded file will be the original file original.txt and the submitted page output text mixed file. What I'm missing here is careful observation. If I see something wrong below, I immediately look up the code, but I don't find that the text above is the content I need. Once I find this part of the content, you may quickly figure out how to solve this problem, that is, close the output of the text content of the page submitted.

At this point, our problem is solved and the text file link is clicked to trigger the download dialog.

Related articles: