Use php to implement forced downloading of files, and header functions are often used.
Example, php file download example.
-
- class Downfile {
- function downserver($file_name){
- $file_path = "./img/".$file_name;
- //Transcoding, the file name is converted 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");
- //Define the size of each download by leaving the variable empty
- $buffer = 1024;
- //Get the size of the file
- $file_size = filesize($file_path);
- / /header("Content-type:text/html;charset=gb2312");
- //Will write the four http protocol information used
- header("Content-type:application/octet-stream");
- header(" Accept-Ranges:bytes");//You can ignore it
- header("Content-Length: ".$file_size);//The original text here is Accept-Length. After checking the http protocol, there is no such item
- header("Content-Disposition:attachment ;filename=".$file_name);
- //Byte counter, records the current number of bytes
- $count = 0;
- while(!feof($fp) && $file_size-$count>0){
- / /Read $buffer-sized data each 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);
- }
- }
- ?>
-
Copy code
Call this function to pass in the file name to download the file. Pay attention to modifying $file_path in the above code.
|