This article mainly introduces the principle of php file download. For more information, see section 1. php download principle.
2. file download source code:
The code is as follows:
<? Php
$ File_name = "haha.jpg"; // file to be downloaded
$ File_name = iconv ("UTF-8", "gb2312", "$ file_name ");
$ Fp = fopen ($ file_name, "r +"); // to download a file, you must first open the file and write it to the memory.
If (! File_exists ($ file_name) {// checks whether a file exists.
Echo "the file does not exist ";
Exit ();
}
$ File_size = filesize ("a.jpg"); // you can specify the file size.
// Returned file
Header ("Content-type: application/octet-stream ");
// Return in byte format
Header ("Accept-Ranges: bytes ");
// Returns the file size.
Header ("Accept-Length:". $ file_size );
// The client dialog box appears, with the corresponding file name
Header ("Content-Disposition: attachment; filename =". $ file_name );
// Prevents instantaneous server load increases and reads data in segments
$ Buffer = 1024;
While (! Feof ($ fp )){
$ File_data = fread ($ fp, $ buffer );
Echo $ file_data;
}
// Close the file
Fclose ($ fp );
?>
3. Solution to file encoding problems:
If the file name is Chinese, php functions cannot recognize the Chinese file name. generally, if the program code is UTF-8, php functions are old and can only recognize the Chinese characters encoded in gb2312, therefore, the iconv ("original encoding", "encoding to be converted", and "string to be transcoded") function can be used for transcoding.
For example, transcode a string from UTF-8 to gb2312
$ File_name = iconv ("UTF-8", "gb2312", "$ file_name ");