记录一个php强制下载文件函数

时间:2024-10-28 21:04:56

整理个经常用的强制下载文件的函数,之前就说把一些常用的东西整理出来结果老是没时间,最近陆续把这些东西整理下。

	public function download()
{
$id = $this->_get('id');
$M = M("downloads");
$data=$M->where("id=$id and status=1")->find();
!$data && exit;
$filename = iconv('UTF-8','GBK',$data['filename']);
$savename = $data['savename'];
$myfile = $data[url] ? $data[url] : 'Uploads/file/'.$savename;
if(file_exists($myfile)){
  $M->where("id=$id")->setInc('downloads');
  $file = @ fopen($myfile, "r");
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=" .$filename );
  while (!feof($file)) {
echo fread($file, 50000);
  }
  fclose($file);
  exit;
}else{
  echo '文件不存在!';
}
}