Home  >  Article  >  Backend Development  >  Implement browser click download of TXT document through PHP (transfer)_PHP tutorial

Implement browser click download of TXT document through PHP (transfer)_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:13:581025browse

Since current browsers can already recognize the txt document format, if you only make a text link to the txt document, it will only open a new window to display the content of the txt file after clicking, and the purpose of clicking to download cannot be achieved. Of course, the solution to this problem can also be to rename the txt file to a file that the browser does not recognize (such as rar). In this case, because the browser cannot recognize the rar type file, the user can only download it. Another way is to use code to set the format of the document through the header to achieve the purpose of click download.

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 Content-Type to application/force-download;
The second header function sets the file to be downloaded. Note that filename here is a file name that does not include a path. The value of filename will be the file name in the dialog box that pops up after clicking download. If there is a path, the file name in the dialog box that pops up is unknown;
Finally, the readfile function is used , output the file stream to the browser, thus realizing the download of txt file.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440324.htmlTechArticleSince modern browsers can already recognize the txt document format, if you only want to make a text link to the txt document, click Afterwards, just opening a new window to display the contents of the txt file does not work...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn