php文件下载记录,分享一个PHP文件下载类

不多说,请见代码:class downLoad{

var $file_name;

var $file_dir;

var $buffer_size = 1024;

var $err = "";

public static $MIME_type = array(

"pdf"  =>"application/pdf",

"exe"  =>"application/octet-stream",

"zip"  =>"application/zip",

"doc"  =>"application/msword",

"xls"  =>"application/vnd.ms-excel",

"ppt"  =>"application/vnd.ms-powerpoint",

"gif"  =>"image/gif",

"png"  =>"image/png",

"jpeg" =>"jpg",

"mp3"  =>"audio/mpeg",

"wav"  =>"audio/x-wav",

"mpeg" =>"mpg",

"mpe"  =>"video/mpeg",

"mov"  =>"video/quicktime",

"avi"  =>"video/x-msvideo",

);

public function __construct($file_dir="",$file_name=""){

$this->file_dir  = $file_dir;

$this->file_name = $file_name;

$this->path = $file_dir."/".$file_name;

$this->suffix = pathinfo($file_name,PATHINFO_EXTENSION);

}

public function down(){

if(!file_exists($this->path)){

$this->err = "该文件被移除了";

return false;

}

$content_type = $this->getMIME($this->suffix);

$file_size = filesize($this->path);

header("Content-type: ".$content_type);

header('Content-Disposition: attachment; filename="'.$this->file_name.'"');

@header("Cache-control: public");

@header("Pragma: public");

header("Content-Length: ".$file_size);

ob_end_clean();

//readfile($this->path); 一次性读出来

$fp= fopen($this->path,"r");

$buffer_size = $this->buffer_size;

$cur_pos = 0; //记录读了多少了

while(!feof($fp) && $file_size>$buffer_size+$cur_pos){

$buffer = fread($fp,$buffer_size); //每次读1024字节

echo $buffer;

$cur_pos += $buffer_size;

}

//把剩下的读出来 因为文件的带下很有很能不是1024 的整数倍

$buffer = fread($fp,$file_size-$cur_pos);

echo $buffer;

fclose($fp);

return true;

}

public function getMIME($key=""){

if($key == "" || !isset(self::$MIME_type[$key])){

return "application/octet-stream";

}

return self::$MIME_type[$key];

}

}

//  $x = new downLoad($file_dir,$file_name);  $file_dir路径 比如 all     $file_name文件名 比如 a.exe  合起来就是全部的路径了all/a.exe

//  $x->down();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值