php下载文件的一种方式
<?php ob_start(); // $file_name="cookie.jpg"; $file_name="abc.jpg"; //用以解决中文不能显示出来的问题 $file_name=iconv("utf-8","gb2312",$file_name); //$file_sub_path=$_SERVER['DOCUMENT_ROOT']."marcofly/phpstudy/down/down/"; $file_sub_path=$_SERVER['DOCUMENT_ROOT']; $file_path=$file_sub_path.$file_name; //首先要判断给定的文件存在与否 if(!file_exists($file_path)){ echo "没有该文件文件"; return ; } $fp=fopen($file_path,"r"); $file_size=filesize($file_path); //下载文件需要用到的头 ob_end_clean(); Header("Content-type: application/octet-stream"); //Header("Content-type: image/jpeg"); Header("Accept-Ranges: bytes"); Header("Accept-Length:".$file_size); //Header("Content-Disposition: attachment; filename=".basename($file_name)); Header("Content-Disposition: attachment; filename=".$file_name); $buffer=1024; $file_count=0; //向浏览器返回数据 while(!feof($fp) && $file_count<$file_size){ $file_con=fread($fp,$buffer); $file_count+=$buffer; echo $file_con; } @fclose($fp); exit(0); /* 第二种方法 */ /* ob_start(); $file_name="123.jpg"; $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"); //输入文件标签 ob_end_clean();Header("Content-type: application/octet-stream");Header("Accept-Ranges: bytes");Header("Accept-Length: ".filesize($file_name));Header($con_dis); //输出文件内容 //读取文件内容并直接输出到浏览器 echo fread($file, filesize($file_name));@fclose($file); exit(0); } */ /* echo $_SERVER["HTTP_USER_AGENT"]; echo "<br/>"; echo $_SERVER['DOCUMENT_ROOT']; */ ?>