Php file download instance code
|
If you use php to implement forced file download, the header function is usually used. Example: PHP file download instance.
- Class Downfile {
- Function downserver ($ file_name ){
- $ File_path = "./img/". $ file_name;
- // Transcode and convert the file name to gb2312 to solve Chinese garbled characters
- $ File_name = iconv ("UTF-8", "gb2312", $ file_name );
- $ File_path = iconv ("UTF-8", "gb2312", $ file_path );
- $ Fp = fopen ($ file_path, "r") or exit ("file does not exist ");
- // The definition variable is empty with the size of each download
- $ Buffer = 1024;
- // Get the file size
- $ File_size = filesize ($ file_path );
- // Header ("Content-type: text/html; charset = gb2312 ");
- // Write the four http protocols used
- Header ("Content-type: application/octet-stream ");
- Header ("Accept-Ranges: bytes"); // can be ignored
- Header ("Content-Length:". $ file_size); // The original text is Accept-Length. this item is not found in the http protocol.
- Header ("Content-Disposition: attachment; filename =". $ file_name );
- // Byte technician, which records the current number of bytes
- $ Count = 0;
- While (! Feof ($ fp) & $ file_size-$ count> 0 ){
- // Read $ buffer size data every time from the file stream opened by $ fp
- $ File_data = fread ($ fp, $ buffer );
- $ Count + = $ buffer;
- // Read the read data
- Echo $ file_data;
- }
- // Close the file stream
- Fclose ($ fp );
- }
- }
- ?>
Call this function to input a file name to download the file. pay attention to modifying $ file_path in the above code. |