tonight we're going to talk about the principles of Web file download, and I'll combine the code to give you an analysis.
function Download ($file _name) {
Header ("Content-type:text/html;charset=utf-8");
//You can convert the file name with Chinese characters to avoid the file_exists function does not know Chinese!
$file _name = Iconv ("Utf-8", "gb2312", $file _name);
$path = $_server[' document_root '); //Get the Absolute directory of downloaded files
$file _path = $path. ' /'. $file _name; //Stitching the path of the file that will be downloaded
if (!file_exists ($file _path)) {
Echo ' The file to download does not exist! ';
Exit ();
}
//share the downloaded file, must first read into the memory
Note: Any file operation downloaded from the server must first be read into memory on the service side
$fp = fopen ($file _path, ' R ');
$file _size = filesize ($file _path); Get the total size of a file
//php download files need to use the header
With this code, the client browser is able to know the file form returned by the server.
Header ("Content-type:application/octet-stream");
Header ("Accept-ranges:bytes");//Description File Transfer Unit is byte
Header ("Accept-length:". $file _size);//Because it is an HTTP protocol transmission, it must indicate the length to be received
//Tell the browser to download the name of the returned file
Header ("content-disposition:attachment; Filename= ". $file _name);
$buffer = 1024;//Avoid causing great pressure on the server, so read 1024 bytes at a time
$file _count = 0;
//feof: Read to end of file
while (!feof ($fp) && $file _count< $file _size) {
//Through fopen, the file has been put into memory! Now read fread from memory is download
$file _content = fread ($fp, $buffer);//$file _content: The contents of each file read
$file _count + = $buffer;
echo $file _content;//Echo reads the content every time, just like a 1.1-point download
}
Fclose ($FP);
}
?>
Today we simply explained the principle of file download, I hope we will do the download function, some of the inspiration, that is enough!
The above describes the principle of Web site file download, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.