PHP如何强制下载文件

很多网站都需要做文件下载的功能.如果直接给连接的方式下载的话有很多的弊处。。。因为有时候需要对下载权限的检查,对下载次数的检查.所以一般采用php的方法进行安全下载.但是下载的时候如果是txt jpg或者pdf等一些浏览器可以直接识别的格式那么浏览器会默认选择直接在浏览器打开而不是保存在本机上。

但是有时我们不想让浏览器直接打开文件,如PDF文件,而是要直接下载文件,那么以下函数可以强制下载文件,函数中使用了application/octet-stream头类型。

代码如下:

function download($filename){ 
    if ((isset($filename))&&(file_exists($filename))){ 
       header("Content-length: ".filesize($filename)); 
       header('Content-Type: application/octet-stream'); 
       header('Content-Disposition: attachment; filename="' . $filename . '"'); 
       readfile("$filename"); 
    } else { 
       echo "Looks like file does not exist!"; 
    } 
}

使用方法如下:

download('/down/test_45f73e852.zip');
/**
 * 下载
 * @param [type] $filename [description]
 * @param string $dir  [description]
 * @return [type]   [description]
 */
function downloads($filename,$dir='./'){
 $filepath = $dir.$filename;
 if (!file_exists($filepath)){
  header("Content-type: text/html; charset=utf-8");
  echo "File not found!";
  exit;
 } else {
  $file = fopen($filepath,"r");
  Header("Content-type: application/octet-stream");
  Header("Accept-Ranges: bytes");
  Header("Accept-Length: ".filesize($filepath));
  Header("Content-Disposition: attachment; filename=".$filename);
  echo fread($file, filesize($filepath));
  fclose($file);
 }
}
posted @ 2017-12-14 11:58  PHP的那些事  阅读(667)  评论(0编辑  收藏  举报