PHP forces file downloading instead of sharing custom functions opened in the browser_PHP Tutorial

WBOY
Release: 2016-07-13 10:30:11
Original
850 people have browsed it

Sometimes we want content such as pictures, text documents, web pages, mp3, pdf, etc. to be downloaded directly when the corresponding link is clicked instead of displayed on the web page, then we need to forcefully set the header information. The following is a PHP function implementation code that will not produce garbled characters. Other programming languages ​​​​can also refer to it for writing and implementation.

Copy code The code is as follows:

/**
 * Downloader
 *
 * @param $file
 *  path to the file
 * @param $downloadfilename
 *  (null|string) the name you want to use for the file you will be downloaded.
 * (if you don't specify it, use the current file name)
 *
 * @return file stream
 */
function download_file($archivo, $ downloadfilename = null) {

if (file_exists($archivo)) {
$downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $downloadfilename);
header('Content-Transfer-Encoding: binary ');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma : public');
header('Content-Length: ' . filesize($archivo));

ob_clean();
flush();
readfile($archivo);
exit;
}

}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/767085.htmlTechArticleSometimes we want content such as pictures, text documents, web pages, mp3, pdf, etc. to be downloaded directly when the corresponding link is clicked , instead of displaying it on the web page, then you need to forcefully set the header...
Related labels:
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!