Example
The code is as follows: |
Copy code |
<? Php Header ("Content-Type; text/html; charset = utf-8 "); Class DownFile { Public static function File ($ _ path, $ file_name ){ // Solve Chinese garbled characters $ _ Path = $ _ path. $ file_name; // Determine whether a file exists If (! File_exists ($ _ path )){ Exit ('file does not exist '); } $ _ Path = iconv ('utf-8', 'gb2312', $ _ path ); $ File_size = filesize ($ _ path ); $ Fp = fopen ($ _ path, 'r '); Header ("Content-type: application/octet-stream "); Header ("Accept-Ranges: bytes "); Header ("Accept-Length: $ file_name "); Header ("Content-Disposition: attachment; filename = $ file_name "); $ Buffer = 1024; $ File_count = 0; While (! Feof ($ fp) & ($ file_size-$ file_count> 0 )){ $ File_data = fread ($ fp, $ buffer ); $ File_count + = $ buffer; Echo $ file_data; } Fclose ($ fp ); } } // Path $ Path = '../'; // File name $ File_name = 'filelist. Php '; DownFile: File ($ path, $ file_name ); ?> |
Analysis and Research
The header function can be used to download scripts on the server without packaging them. For example, PHP or html files, the core statement in the preceding example is
The code is as follows: |
Copy code |
$ _ Path = iconv ('utf-8', 'gb2312', $ _ path ); $ File_size = filesize ($ _ path ); $ Fp = fopen ($ _ path, 'r '); Header ("Content-type: application/octet-stream "); Header ("Accept-Ranges: bytes "); Header ("Accept-Length: $ file_name "); Header ("Content-Disposition: attachment; filename = $ file_name "); $ Buffer = 1024; $ File_count = 0; While (! Feof ($ fp) & ($ file_size-$ file_count> 0 )){ $ File_data = fread ($ fp, $ buffer ); $ File_count + = $ buffer; Echo $ file_data; } |
In the following three sentences, convert the file name encoding to prevent Chinese garbled characters. The first is to get the file size, and the third is to use fopen to read the file.
The code is as follows: |
Copy code |
$ _ Path = iconv ('utf-8', 'gb2312', $ _ path ); $ File_size = filesize ($ _ path ); $ Fp = fopen ($ _ path, 'r '); |
The following lines of code tell the browser what the content and file name of the file we want to send
The code is as follows: |
Copy code |
Header ("Content-type: application/octet-stream "); Header ("Accept-Ranges: bytes "); Header ("Accept-Length: $ file_name "); Header ("Content-Disposition: attachment; filename = $ file_name "); |
The following three lines tell us that the maximum download duration cannot exceed 1 MB, and the Download continues until the file is downloaded.
The code is as follows: |
Copy code |
$ Buffer = 1024; $ File_count = 0; While (! Feof ($ fp) & ($ file_size-$ file_count> 0 )){ $ File_data = fread ($ fp, $ buffer ); $ File_count + = $ buffer; Echo $ file_data; |