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
$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.