您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php实现打包下载文件的代码示例

2025/4/18 14:08:34发布38次查看
这篇文章主要介绍了php实现打包下载文件的方法,涉及php基于curl的文件获取、遍历、zip压缩及下载等相关操作技巧,需要的朋友可以参考下
本文实例讲述了php实现打包下载文件的方法。分享给大家供大家参考,具体如下:
/** * 下载文件 * @param $img * @return string */ public function download($img) { $items = []; $names = []; if($img) { //用于前端跳转zip链接拼接 $path_redirect = '/zip/'.date('ymd'); //临时文件存储地址 $path = '/tmp'.$path_redirect; if(!is_dir($path)) { mkdir($path, 0777,true); } foreach ($img as $key => $value) { $filecontent = ''; $filecontent = $this->curldownload($value['url']); if( $filecontent ) { $__tmp = $this->savefile( $value['url'] , $path , $filecontent ); $items[] = $__tmp[0]; $names[] = $value['name'].'_'.($key+1).'.'.$__tmp[1]; } } if( $items ) { $zip = new ziparchive(); $filename = time().'download.zip'; $zipname = $path.'/'.$filename; if (!file_exists($zipname)) { $res = $zip->open($zipname, ziparchive::create | ziparchive::overwrite); if ($res) { foreach ($items as $k => $v) { $value = explode("/", $v); $end = end($value); $zip->addfile($v, $end); $zip->renamename($end, $names[$k]); } $zip->close(); } else { return ''; } //通过前端js跳转zip地址下载,让不使用php代码下载zip文件 //if (file_exists($zipname)) { //拼接附件地址 //$redirect = 域名.$path_redirect.'/'.$filename; //return $redirect; //header("location:".$redirect); //} //直接写文件的方式下载到客户端 if (file_exists($zipname)) { header("cache-control: public"); header("content-description: file transfer"); header('content-disposition: attachment; filename=附件.zip'); //文件名 header("content-type: application/zip"); //zip格式的 header("content-transfer-encoding: binary"); //告诉浏览器,这是二进制文件 header('content-length: ' . filesize($zipname)); //告诉浏览器,文件大小 @readfile($zipname); } //删除临时文件 @unlink($zipname); } } return ''; } } /** * curl获取链接内容 * @param $url * @return mixed|string */ public function curldownload($url) { $ch = curl_init($url); curl_setopt($ch, curlopt_ipresolve, curl_ipresolve_v4); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_header, 0); curl_setopt($ch, curlopt_connecttimeout, 20); curl_setopt($ch, curlopt_ssl_verifypeer, false); curl_setopt($ch, curlopt_ssl_verifyhost, false); $errno = curl_errno($ch); $error = curl_error($ch); $res=curl_exec($ch); curl_close($ch); if($errno>0){ return ''; } return $res; } /** * 保存临时文件 * @param $url * @param $dir * @param $content * @return array */ public function savefile( $url ,$dir , $content) { $fname = basename($url); //返回路径中的文件名部分 $str_name = pathinfo($fname); //以数组的形式返回文件路径的信息 $extname = strtolower($str_name['extension']); //把扩展名转换成小写 $path = $dir.'/'.md5($url).$extname; $fp = fopen( $path ,'w+' ); fwrite( $fp , $content ); fclose($fp); return array( $path , $extname) ; }
引用:
$img = [['url'=>'地址url/1.jpg','name'=>'名字']]; download($img);
以上就是php实现打包下载文件的代码示例的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product