[php] thinkphp基于Http类 下载文件

不熟悉的可以去Org/Net/Http 看看Http.class.php类文件 


一、使用curlDownload 采集远程文件

/**  * 采集远程文件  * @access public  * @param string $remote 远程文件名  * @param string $local 本地保存文件名  * @return mixed  */ static public function curlDownload($remote,$local) {
    $cp = curl_init($remote);
    $fp = fopen($local,"w");
    curl_setopt($cp, CURLOPT_FILE, $fp);
    curl_setopt($cp, CURLOPT_HEADER, 0);
    curl_exec($cp);
    curl_close($cp);
    fclose($fp);
}


调用:

$Http = new \Org\Net\Http();
$Http::curlDownload("http://h.hiphotos.baidu.com/image/pic/item/b64543a98226cffc9153e5b3bb014a90f603eab2.jpg", "./Public/file/1.jpg");

二、使用download 下载文件

/**  * 下载文件  * 可以指定下载显示的文件名,并自动发送相应的Header信息  * 如果指定了content参数,则下载该参数的内容  * @static  * @access public  * @param string $filename 下载文件名  * @param string $showname 下载显示的文件名  * @param string $content 下载的内容  * @param integer $expire 下载内容浏览器缓存时间  * @return void  */  static public function download ($filename, $showname='',$content='',$expire=180) {
      if(is_file($filename)) {
          $length = filesize($filename);
      }elseif(is_file(UPLOAD_PATH.$filename)) {
          $filename = UPLOAD_PATH.$filename;
          $length = filesize($filename);
      }elseif($content != '') {
          $length = strlen($content);
      }else {
          E($filename.L('下载文件不存在!'));
      }
      if(empty($showname)) {
          $showname = $filename;
      }
      $showname = basename($showname);
if(!empty($filename)) {
   $finfo     = new \finfo(FILEINFO_MIME);
   $type  = $finfo->file($filename);         
}else{
   $type  = "application/octet-stream";
}
      //发送Http Header信息 开始下载  header("Pragma: public");
      header("Cache-control: max-age=".$expire);
      //header('Cache-Control: no-store, no-cache, must-revalidate');  header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
      header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
      header("Content-Disposition: attachment; filename=".$showname);
      header("Content-Length: ".$length);
      header("Content-type: ".$type);
      header('Content-Encoding: none');
      header("Content-Transfer-Encoding: binary" );
      if($content == '' ) {
          readfile($filename);
      }else {
       echo($content);
      }
      exit();
  }

调用前,首先要确定有没有开启php_fileinfo扩展,没有的话,则会报错。。

wampserver开启方式:

[php] thinkphp基于Http类 下载文件_第1张图片

选择php_fileinfo就行了


调用:

$Http = new \Org\Net\Http();
$filename="Public/file/test.doc";
$showname="test.doc";
$content = "this";  // 表示下载的文件内容只有this $Http::download($filename, $showname, $content);

谢谢关注~


你可能感兴趣的:([php] thinkphp基于Http类 下载文件)