Implementation of PHP browser click to download TXT document method details

  • 2020-06-03 06:07:58
  • OfStack

Since the current browser can already recognize the txt document format, if only one text link is made to the txt document, the click will only open a new window to display the contents of the txt file, which cannot achieve the purpose of click and download. The solution, of course, would be to rename the txt file to something the browser doesn't recognize (rar, for example), so that the browser doesn't recognize the rar file, so the user has to download it. Another option is to use the header code to format the document for click-to-download purposes.
The PHP code is as follows:
===========================================================
$filename = '/ path/'. $_GET [' file']. 'txt'; // File path
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=".basename($filename));
readfile($filename);
===========================================================
Brief description:
The first header function sets the value of ES29en-ES30en to application/ ES32en-ES33en.
The second header function sets the file to download. Note that filename does not contain the filename of the path. The value of filename will be the filename in the popup dialog after clicking download. If there is a path, the filename of the popup dialog is unknown.
Finally, the readfile function outputs the file stream to the browser, thus realizing the download of the txt file.


Related articles: