Force download of files in php_PHP tutorial

WBOY
Release: 2016-07-13 17:35:02
Original
924 people have browsed it

Since current browsers can already recognize the document format of txt, if you just make a text link to the txt document, it may only open a new window to display the content of the txt file, and the purpose of clicking to download cannot be achieved. We have to do something else.
Of course, the solution to this problem can also be to rename your txt file to a file that the browser does not recognize, such as rar. If you click on it, the browser will not recognize it and will have to let the user download it.

The following file is used to set the format of the document by setting the header to achieve the purpose of click download. Click the file passed from the previous page to download.

$filename = "/somepath/".$_GET[file].".txt"; //The name of the file to be downloaded

header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=".basename($filename));
readfile($filename);

?>

First: Set the value of Content-Type to application/force-download to force download

Then the second header function sets the file to be downloaded. Note that filename here is a file name that does not include a path, so basename is used to filter out the path name. The value of this filename will be the file name in the dialog box that pops up after clicking download.

The last step is readfile, which outputs the file stream to the browser, thus realizing the download of txt files. Other types are similar.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508422.htmlTechArticleSince current browsers can already recognize the document format of txt, so if you just create a text for the txt document If you link, it may just open a new window to display the txt file...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!