Home > Backend Development > PHP Tutorial > PHP implements download file function

PHP implements download file function

WBOY
Release: 2016-08-08 09:19:30
Original
877 people have browsed it

PHP code to implement the download function, download files from the server to the local:

Public function downloadTemplateAction()

{
define('Z_WEB_ROOT','http://'.$_SERVER[" SERVER_NAME"]); --------host
$file_name = "template.xlsx";
$file_dir = Z_WEB_ROOT."/SITE/public/template/"; -----The directory where the file is located
$file = @ fopen($file_dir . $file_name,"r");
if (!$file) {
echo "File does not exist. ";
} else {
Header("Content-type: application/octet-stream");
Header("Content-Disposition: attachment; filename=" . $file_name);
while (!feof ($file)) {
echo fread($file,50000);
}
fclose ($file);
}

}

Detailed explanation:

The role of Header("Content-type: application/octet-stream"): With this code, the browser can know the file form returned by the server . The role of

Header("Content-Disposition: attachment; filename=".$file_name): tells the browser the name of the file returned.

fclose($file) can output the last remaining data in the buffer to a disk file and release the file pointer and related buffers.

The above has introduced the function of downloading files in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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