The instructions in the PHP help document about PHP triggering downloads through headers are relatively simple, and there are very few articles on this aspect on the Internet, and many articles cannot achieve the desired effect. Today I will also talk about this topic. If you feel that it is improved compared to some articles on the Internet, then I will be very satisfied.
From an accurate point of view, the PHP document is the most accurate, because it succinctly lists the three statements required to trigger the download of text files. Taking PDF as an example:
The following is the quoted content:
// 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 correct, but some unforeseen problems can easily occur during actual use. If you are a very careful person, you can easily avoid these problems. But I am not, so I encountered such a problem. Here I will briefly talk about my problem.
For the first sentence, there should be nothing to say. It is necessary. Just change the type of the document. For example, if you are downloading a txt file, then change it to header('Content-type: application/txt');. The second sentence There is nothing to say, just give your downloaded document a name. If it is a txt file, you can change it to header('Content-Disposition: attachment; filename="downloaded.txt"');, the third sentence question There are more. The readfile function means to read a file and output it. The path of the file here needs to be the real file path. If it is an original.txt file under the downloads folder, you can write readfile('downloads/ original.txt');, and if the submitted page will output text and other characters, the downloaded file will be a mixed file of the original file original.txt and the text output by the submitted page. I lacked careful observation here. As soon as I saw something was wrong, I immediately checked the code, but did not find that the above text was what I needed. After discovering this part of the content, you may quickly think of how to solve this problem. , that is, turning off the output of the text content of the submitted page. At this point, the problem is solved, and the download dialog box is triggered when the text file link is clicked.