This file download instance is very detailed. It is combined with the header function and the while fread function to split the file and read it and then send it to the client. It is considered a standard file download instance.
A small PHP File Download instance
/* ===================================================== ======================
$ FileName is the file name, required
$ FilePath is the file path. Optional. It can be a relative or absolute path.
The path can only consist of English letters and data, and cannot contain Chinese characters.
If you have any questions, contact the blogger.
========================================================== =================== */
The Code is as follows: |
Copy code |
<? Php Header ("Content-type: text/html; charset = UTF-8 "); If (strlen ($ FileName) <= 3) {echo "Download failed: Your downloaded file information is incorrect"; return ;} $ FileName = iconv ("UTF-8", "gb2312", $ FileName); // convert the file name format to prevent Chinese garbled characters // Start to determine the path If (! Is_null ($ FilePath) & strlen ($ FilePath)> 1 ){
If (substr ($ FilePath,) = '/') {// determine whether the path is an absolute path
$ FilePath = $ _ SERVER ['document _ root']. $ FilePath;
} If (substr ($ FilePath,-1 )! = "/") {// Check whether the end is/
$ FilePath = $ FilePath .'/';
} If (is_numeric (strpos ($ FilePath, ": \") {// check whether the path is absolute
$ FilePath = str_replace ("/", "\", $ FilePath );
} } Elseif (strlen ($ FilePath) = 1 & $ FilePath! = "/"){
$ FilePath = $ FilePath ."/";
} Else {
$ FilePath = "";
} If (! File_exists ($ FilePath. $ FileName )){
Echo "Download failed: the file to be downloaded is not found"; return;
} /* ===================================================== ============ Send download-related header information ========================================================== =========== */
Header ("Content-type: application/octet-stream ");
Header ("Accept-Ranges: bytes"); // returns the value in bytes.
Header ("Accept-Length: $ FileSize"); // returns the file size.
Header ("Content-Disposition: attachment; filename =". $ FileName); // the pop-up dialog box on the client, with the corresponding file name
/* ===================================================== ============ Start download ========================================================== =========== */ $ FileSize = filesize ($ FilePath. $ FileName );
$ File = fopen ($ FilePath. $ FileName, "r"); // open the File
$ FileBuff = 512;
While ($ FileSize> = 0 ){
$ FileSize-= $ FileBuff;
Echo fread ($ File, $ FileBuff );
}
Fclose ($ File ); } ?> |
Summary
This download instance supports Chinese characters and uft8 encoding at the beginning of the file.