Home >Backend Development >PHP Tutorial >Examples of php using headers to send various types of files for download
The so-called downloading of text files means that when we click on a link to a text file, it does not open it Instead of this file, a download dialog box pops up for us to download. This is the main issue discussed today. 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. From an accurate perspective, the PHP document is the most accurate, because it succinctly lists the three statements required to trigger downloading of text files. Taking PDF as an example:
These three sentences is 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 doesn’t say much, just give your downloaded document a name. If it’s a txt file, you can change it to header(’Content-Disposition: attachment; filename="downloaded.txt”‘); The third sentence has more problems. The readfile function means to read a file and then output it. The path of the file here needs to be a real file path. If it is an original.txt file under the downloads folder, it can be written like this readfile('downloads/original.txt');, and if the submitted page will output text and other characters, then 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. When I saw something was wrong, I immediately checked the code, but I didn’t 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. The problem is to turn off the output of the text content of the page submitted to. The problem is solved, and the download dialog box is triggered when the text file link is clicked. |