---
title: "php 文件下载类"
author: "javaeyeren"
date: "2009-02-02T16:20:00Z"
tags: []
slug: "php"
draft: false
lastmod: "2009-02-02T16:20:00Z"
id: 601316
url: "https://javaeyeren.iteye.com/blog/601316"
---

&lt;?php  
/*  
\* 功 能: 文件下载  
\*/

/\**  
\* 使用方法:$download = new Download();  
\* //设置参数  
\* $download-&gt;set\_file\_dir("c:/");  
\* $download-&gt;set\_file\_name("boot.ini");  
\* $download-&gt;set\_read\_bytes(1024);  
\* //文件下载处理操作  
\* $download-&gt;deal\_with();  
\* //判断文件是否存在  
\* if($download-&gt;is\_file\_exist()){  
\*echo "file\_exist";  
\*}else{  
\*echo "file\_not\_exist";  
\*}  
\*/  
class Download {  
private $file = null;//文件句柄  
private $file\_dir = "";//文件所在的目录  
private $file\_name = "";//文件名称  
private $file\_exist = false;//表示文件是否存在, 缺省为不存在  
private $read\_bytes = 0;//文件读取字节数  
private $mode = "r";//文件的访问类型

public function \_\_construct(){  
}

public function \_\_destruct(){  
if(null != $this-&gt;file){  
fclose($this-&gt;file);  
}  
}

/\**  
\* 文件下载处理的操作  
\*/  
public function deal\_with(){  
//文件全路径  
$file\_path = $this-&gt;file\_dir . $this-&gt;file\_name;

//检查文件是否存在  
if (file\_exists($file\_path)) {  
$this-&gt;file\_exist = true;

// 打开文件  
$this-&gt;file = fopen($file\_path, $this-&gt;mode);

// 输入文件标签  
Header("Content-type: application/octet-stream");  
Header("Accept-Ranges: bytes");  
Header("Accept-Length: " . filesize($file\_path));  
Header("Content-Disposition: attachment; filename=" . $this-&gt;file\_name);

// 输出文件内容  
while(!feof($this-&gt;file))  
{  
$out = fread($this-&gt;file, $this-&gt;read\_bytes);  
if(!get\_magic\_quotes\_gpc())  
{  
echo $out;  
}  
else  
{  
echo stripslashes($out);  
}  
}  
//echo fread($file, filesize($file\_dir . $file\_name));  
}  
}

/\**  
\* 返回值为 true 或 false, 通过其值判断文件是否存在  
\*/  
public function is\_file\_exist(){  
return $this-&gt;file\_exist;  
}

/\**  
\* 参数类型为字符串  
\*/  
public function set\_file\_dir($file\_dir=""){  
$this-&gt;file\_dir = $file\_dir;  
}

/\**  
\* 参数类型为字符串  
\*/  
public function set\_file\_name($file\_name=""){  
$this-&gt;file\_name = $file\_name;  
}

/\**  
\* 参数类型为整型  
\*/  
public function set\_read\_bytes($read\_bytes=1024){  
$this-&gt;read\_bytes = $read\_bytes;  
}  
}  
?&gt;