PHP file download is more common, online information is more, here no longer emphasize how to achieve (because it is also seen on the internet). The following are the main points of attention to download code.
PHP download file is mainly the file in a byte stream output, that is, Echo fread ($file, FileSize ($file _name)), it is important to note that if you have output before (or after) the code, it may be written to the downloaded file, the solution is to use the Ob_start (); and Ob_end_clean (); To clear the preceding output, the output of the rear is directly using the @fclose ($file); exit (0) to resolve.
The code is as follows:
[PHP]View Plaincopy
- Ob_start ();
- $file _name = Iconv ("Utf-8","gb2312",$file _name);
- if (! Is_file ($file _name)) {
- echo "url error!";
- } Else {
- $ua = $_server["Http_user_agent"];
- if (Preg_match ("/msie/", $ua)) {
- $encoded _filename = UrlEncode (basename ($file _name));
- $encoded _filename = Str_replace ("+", "%20", $encoded _filename);
- $con _dis = ' content-disposition:attachment; Filename= '. $encoded _filename. "';
- } Else if (Preg_match ("/firefox/", $ua)) {
- $con _dis = ' content-disposition:attachment; filename*= ' utf8\ '. basename ($file _name). "';
- } Else {
- $con _dis = ' content-disposition:attachment; Filename= '. basename ($file _name). "';
- }
- $file = fopen ($file _name, "R");
- //input file tags
- Ob_end_clean (); Header ("Content-type:application/octet-stream"); Header ("accept-ranges:bytes"); Header ("Accept-length:". ) FileSize ($file _name)); Header ($con _dis);
- //Output file contents
- //Read file contents and output directly to browser
- echo fread ($file, filesize ($file _name)); @fclose ($file);
- exit (0);
- }
PHP Code?
123456789101112131415161718192021222324252627282930313233343536 |
class
FileDown {
public
$fileName
;
public
$fileSize
;
//转码 gb2312
function
__construct(
$fileName
){
$this
->fileName=iconv(
"utf-8"
,
"gb2312"
,
$fileName
);
}
function
Down (){
//$_SERVER[‘DOCUMENT_ROOT‘]当前运行脚本所在的文档根目录。在服务器配置文件中定义。
$path
=
$_SERVER
[
‘DOCUMENT_ROOT‘
].
"/12/"
.
$this
->fileName;
if
(!
file_exists
(
$path
)){
die
(
"文件不存在"
);
}
$fp
=
fopen
(
$path
,
"r"
);
//读入
$this
->
fileSize
=
filesize
(
$path
);
//返回文件的头 浏览器靠头识别下载 //返回
//返回的文件类型 流 可以是文本 二进制
header(
"Content-type: application/octet-stream"
);
//按照字节大小返回
header(
"Accept-Ranges: bytes"
);
//返回文件大小
header(
"Accept-Length: $this->fileSize"
);
//这里客户端的弹出对话框,对应的文件名
header(
"Content-Disposition: attachment; filename="
.
$this
->fileName);
$count
=0;
$buffer
=1024;
while
(!
feof
(
$fp
)&&
$this
->
fileSize
-
$count
>0){
$fileData
=
fread
(
$fp
,
$buffer
);
$count
+=
$buffer
;
echo
$fileData
;
}
fclose(
$fp
);
}
}
$fd
=
new
FileDown(
"白羊座.png"
);
$fd
->Down ();
|
php file Download (solve the problem of more than a few bytes after file download) and encapsulation into class example