php for file download instance sharing

  • 2021-06-28 11:40:46
  • OfStack

Take one case:


<?php
class Downfile {

    function downserver($file_name){
$file_path = "./img/".$file_name;
// Transcoding, file name to gb2312 Solve Chinese garbles 
$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 variables blank for each download 
$buffer = 1024;
// Get the size of the file 
$file_size = filesize($file_path);
//header("Content-type:text/html;charset=gb2312");
// Writing Used 4 strip http Protocol Information 
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");// Ignorable 
header("Content-Length: ".$file_size);// Original text Here is Accept-Length Checked http Agreement does not have this item 
header("Content-Disposition:attachment;filename=".$file_name);
// Byte Technician, recording the current number of bytes 
$count = 0;
while(!feof($fp) && $file_size-$count>0){
// from $fp Read every time in an open file stream $buffer Size data 
$file_data = fread($fp,$buffer);
$count+=$buffer;
// Read the read data 
echo $file_data;
}
// Close File Stream 
fclose($fp);
    }

   }
?>

Calling this function to pass in the file name will download the file, but be careful to modify $file_path


Related articles: