A brief discussion on the principles of website file downloading

WBOY
Release: 2016-07-29 09:08:52
Original
1966 people have browsed it

Tonight let’s talk about the principle of website file downloading. Let me analyze it with the code below. ? & Lt;? PHP Function Download ($ File_name) {

Header ("Content-Type: Text/HTML; Charset = UTF-8"); Conversion to prevent the file_exists function from not understanding Chinese!


$file_name = iconv("utf-8","gb2312",$file_name);
$path = $_SERVER['DOCUMENT_ROOT']';
// Get the absolute directory of the downloaded file $file_path = $ path.'/'.$file_name; // Splice the path of the file to be downloaded
if(!file_exists($file_path)){

echo 'The file to be downloaded does not exist! ';

exit();}


// Sharing downloaded files must first be read into the memory
// Note: Any file operations related to downloading from the server must be done first The server reads the file into memory

$fp = fopen($file_path, 'r');

$file_size = filesize($file_path); // Get the total size of the file
// PHP needs to be used to download files Header // Through this code, the client browser can know the file format returned by the server
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes") ; ; The name of the file returned by the server download

Header("Content-Disposition: attachment; filename=".$file_name); $buffer = 1024;
// Avoid putting a lot of pressure on the server, so only 1024 bytes are read at a time C $ file_count = 0;

// Feof: Read the end of the file
While (! Feof ($ fp) && $ file_count & lt; $ file_size) {
// Through fopen, the file has been put in memory. ! Now read fread from the memory and download it
$file_content = fread($fp, $buffer); ; ; The principle of downloading, I hope it will give you some inspiration when doing downloading functions in the future, that will be enough!



The above has introduced a brief discussion on the principles of website file downloading, including aspects of content. 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