使用PHP实现文件下载

来源:互联网 发布:股票买卖模拟软件 编辑:程序博客网 时间:2024/04/29 20:12

       这里写了如何使用PHP实现文件下载的程序,主要是为了方便自己查找,也为了方便大家查阅学习(当然网上也有其他类似的代码)。其中详细解析看原程序注释。

PHP实现文件下载程序:

FileDownService.class.php

[php] view plain copy
print?
  1. <?php  
  2.     //封装到类  
  3.     class FileDownService {  
  4.         //下载文件的函数  
  5.   
  6.         //对函数的说明  
  7.         //参数说明 $file_name 文件名  
  8.         //         $file_sub_dir 下载文件的子路径 "/xxx/xxx/"  
  9.         function down_file($file_name$file_sub_dir) {  
  10.             //如果文件是中文的  
  11.             //原因 php文件函数,比较古老,需要对中文转码 gb2312  
  12.             $file_name=iconv("utf-8","gb2312"$file_name);  
  13.   
  14.             //使用绝对路径  
  15.             $file_path=$_SERVER['DOCUMENT_ROOT'].$file_sub_dir.$file_name;  
  16.   
  17.             //1.判断文件是否存在  
  18.             if(!file_exists($file_path)) {  
  19.                 echo '文件不存在!';  
  20.                 return;  
  21.             }  
  22.   
  23.             //2.打开文件  
  24.             $fp=fopen($file_path"r");  
  25.   
  26.             //3.获取下载文件的大小  
  27.             $file_size=filesize($file_path);  
  28.   
  29.             //限制下载文件的大小  
  30.             /*if($file_size>10*1024*1024) { 
  31.                 echo "<script language='javascript'>window.alert('文件过大')</script>"; 
  32.                 return ; 
  33.             }*/  
  34.   
  35.             //4.添加http的响应信息  
  36.             //返回的是文件  
  37.             header("Content-type: application/octet-stream");  
  38.             //按照字节大小返回  
  39.             header("Accept-Ranges: bytes");  
  40.             //返回文件大小  
  41.             header("Accept-Length: ".$file_size);  
  42.             //这里客户端的弹出对话框,对应的文件名  
  43.             header("Content-Disposition: attachment; filename=".$file_name);  
  44.   
  45.             //5.向客户端回送数据  
  46.             $buffer=1024;  
  47.   
  48.             //为了下载的安全,我们最好做一个文件字节读取计数器  
  49.             $file_count=0;  
  50.             //这句话用于判断文件是否结束  
  51.             while(!feof($fp) && $file_size-$file_count>0) {  
  52.                 $file_data=fread($fp$buffer);  
  53.                 //统计读了多少个字节  
  54.                 $file_count+=$buffer;  
  55.                 //把部分数据回送给浏览器  
  56.                 echo $file_data;  
  57.             }  
  58.   
  59.             //6.关闭文件  
  60.             fclose($fp);  
  61.         }  
  62.     }  
  63. ?>  

0 0