common.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. <?php
  2. // 应用公共文件
  3. use think\facade\Config;
  4. use think\facade\Db;
  5. use think\facade\Filesystem;
  6. use tp5er\thinkCsv\Export;
  7. // 应用公共文件
  8. function app_show($code=0,$message="",$data=[]){
  9. $result = ['code'=>$code,"message"=>$message,"data"=>$data];
  10. return json($result);
  11. }
  12. // 应用公共文件
  13. function error_show($code=0,$message=""){
  14. $result = ['code'=>$code,"message"=>$message];
  15. return json($result);
  16. }
  17. function GetUserInfo($token){
  18. $host = Config::get("app");
  19. $url = $host["api_host"]."/verifyToken";
  20. $data=[
  21. "token"=>$token
  22. ];
  23. $response=curl_request($url,$data);
  24. return json_decode($response,true);
  25. }
  26. function setUserCompany($condition){
  27. $host = Config::get("app");
  28. $url = $host["api_host"]."/setcompany";
  29. $response=curl_request($url,$condition);
  30. return json_decode($response,true);
  31. }
  32. function setCompanyStatus($condition){
  33. $host = Config::get("app");
  34. $url = $host["api_host"]."/companystatus";
  35. $response=curl_request($url,$condition);
  36. return json_decode($response,true);
  37. }
  38. function setStatus($condition){
  39. $host = Config::get("app");
  40. $url = $host["api_host"]."/userstatus";
  41. $response=curl_request($url,$condition);
  42. return json_decode($response,true);
  43. }
  44. /**手机号验证
  45. * @param $mobile
  46. * @return bool
  47. */
  48. function checkMobile($mobile){
  49. if (!is_numeric($mobile)) {
  50. return false;
  51. }
  52. return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
  53. }
  54. function checkTel($tel){
  55. if (!$tel) {
  56. return false;
  57. }
  58. return preg_match('/^(0[0-9]{2,3}\-)([0-9]{7,8})+(\-[0-9]{1,4})?$/', $tel) ? true : false;
  59. }
  60. /**邮箱验证
  61. * @param $email
  62. * @return bool
  63. */
  64. function checkEmail($email){
  65. if (!$email) {
  66. return false;
  67. }
  68. return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $email) ? true : false;
  69. }
  70. /**
  71. * @param
  72. * @return int
  73. */
  74. function makeSalt(){
  75. $salt = rand(10000000,99999999);
  76. return $salt;
  77. }
  78. /**
  79. * @param $token
  80. * @return array
  81. * @throws \think\db\exception\DataNotFoundException
  82. * @throws \think\db\exception\DbException
  83. * @throws \think\db\exception\ModelNotFoundException
  84. * @throws \think\exception\DbException
  85. */
  86. function VerifyTokens($token){
  87. $host = Config::get("app");
  88. $url = $host["api_host"]."/verifyToken";
  89. $data=[
  90. "token"=>$token
  91. ];
  92. $response=curl_request($url,$data);
  93. return json_decode($response,true);
  94. }
  95. /**
  96. * @param $token
  97. * @param $condition
  98. * @return mixed
  99. */
  100. function GetUserlist($condition){
  101. $host = Config::get("app");
  102. $url = $host["api_host"]."/userlistbycompany";
  103. $response=curl_request($url,$condition);
  104. return json_decode($response,true);
  105. }
  106. ///**
  107. // * @param $token
  108. // * @param $condition
  109. // * @return mixed
  110. // */
  111. //function GetAccountall($token, $condition){
  112. // $host = Config::get("app");
  113. //
  114. // $url = $host["api_host"]."/Api/userall";
  115. // $condition['token']=$token;
  116. // $response=curl_request($url,$condition);
  117. //
  118. // return json_decode($response,true);
  119. //}
  120. function GetList($condition){
  121. $host = Config::get("app");
  122. $url = $host["api_host"]."/userlist";
  123. $response=curl_request($url,$condition);
  124. return json_decode($response,true);
  125. }
  126. /**
  127. * @param $token
  128. * @param $condition ['id'=>1]
  129. * @return mixed
  130. */
  131. function GetInfoById($token,$condition){
  132. $host = Config::get("app");
  133. $url = $host["api_host"]."/userinfo";
  134. $condition['token']=$token;
  135. $response=curl_request($url,$condition);
  136. return json_decode($response,true);
  137. }
  138. /**
  139. * @param $str
  140. * @return string
  141. */
  142. function makeNo($str){
  143. $date=date("mdHis");
  144. $year = date("Y")-2000;
  145. $msec=rand(1000,9999);
  146. return $str.$year.$date.$msec;
  147. }
  148. function makeStr($str){
  149. $date=date("mdHis");
  150. $year = date("Y")-2000;
  151. $msec=randomkeys(4);
  152. return $str.$msec.$year.$date;
  153. }
  154. function randomkeys($length) {
  155. $returnStr='';
  156. $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
  157. for($i = 0; $i < $length; $i ++) {
  158. $returnStr .= $pattern[mt_rand ( 0, strlen($pattern)-1 )]; //生成php随机数
  159. }
  160. return $returnStr;
  161. }
  162. /**
  163. * @param $token
  164. * @param $condition
  165. * @return mixed
  166. */
  167. function resetpwd($condition){
  168. $host = Config::get("app");
  169. $url = $host["api_host"]."/setpasswd";
  170. $response=curl_request($url,$condition);
  171. return json_decode($response,true);
  172. }
  173. function resetpasswd($token,$condition){
  174. $host = Config::get("app");
  175. $url = $host["api_host"]."/Api/passsave";
  176. $condition['token']=$token;
  177. $response=curl_request($url,$condition);
  178. return json_decode($response,true);
  179. }
  180. /**
  181. * @param $condition
  182. * @return array|bool|float|int|mixed|\stdClass|string|null
  183. */
  184. function checkLogin($condition){
  185. $host = Config::get("app");
  186. $url = $host["api_host"]."/login";
  187. $response=curl_request($url,$condition);
  188. return json_decode($response,true);
  189. }
  190. /**
  191. * @param $token
  192. * @param $condition
  193. * @return mixed
  194. */
  195. function resetinfo($condition){
  196. $host = Config::get("app");
  197. $url = $host["api_host"]."/usersave";
  198. $response=curl_request($url,$condition);
  199. return json_decode($response,true);
  200. }
  201. /**
  202. * @param $condition
  203. * @return array|bool|float|int|mixed|\stdClass|string|null
  204. */
  205. function addacount($condition){
  206. $host = Config::get("app");
  207. $url = $host["api_host"]."/useradd";
  208. $response=curl_request($url,$condition);
  209. return json_decode($response,true);
  210. }
  211. //获取用户所绑定的公司列表
  212. if(function_exists('get_company_list') == false){
  213. function get_company_list(array $data=[]){
  214. $host = Config::get("app");
  215. $url = $host["api_host"]."/get_company_list";
  216. $response=curl_request($url,$data);
  217. echo $response;exit;
  218. // return json_decode($response,true);
  219. }
  220. }
  221. if(!function_exists("headerSign")){
  222. function headerSign($post){
  223. $config = Config::get("sign");
  224. $appid=$config['appid'];
  225. $appkey=$config['appkey'];
  226. $headerArr=["appid"=>'123',"noce"=>randomkeys(16),"sign"=>'',"timestamp"=>time()];
  227. $value =array_merge($post,$headerArr);
  228. $Sign= new \Sign($appid,$appkey);
  229. $headerArr['sign'] = $Sign->makeSign($value);
  230. $list=["Content-Type"=>"multipart/json;charset=utf-8"];
  231. foreach ($headerArr as $key=>$value){
  232. $list[]=$key.":".$value;
  233. }
  234. return $list;
  235. }
  236. }
  237. //参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
  238. function curl_request($url,$post='',$header=[]){
  239. // $header = empty($header) ? '' : $header;
  240. $header = headerSign($post);
  241. if(is_array($post)) $post=http_build_query($post);
  242. $curl = curl_init();
  243. curl_setopt($curl, CURLOPT_URL, $url);
  244. curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
  245. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  246. curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
  247. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  248. if($post) {
  249. curl_setopt($curl, CURLOPT_POST, 1);
  250. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  251. }
  252. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  253. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  254. curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  255. $data = curl_exec($curl);
  256. if (curl_errno($curl)) {
  257. return curl_error($curl);
  258. }
  259. curl_close($curl);
  260. return $data;
  261. }
  262. /**
  263. * @param $roleid
  264. * @param $menu
  265. * @return bool
  266. * @throws \think\db\exception\DataNotFoundException
  267. * @throws \think\db\exception\DbException
  268. * @throws \think\db\exception\ModelNotFoundException
  269. */
  270. function checkRole($roleid,$menu){
  271. $roleinfo = \think\facade\Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
  272. if($roleinfo['private_data']!=""){
  273. $private = explode(",",$roleinfo['private_data']);
  274. if(in_array($menu,$private)){
  275. return true;
  276. }
  277. }
  278. return false;
  279. }
  280. /**
  281. * @param $row
  282. * @param $list
  283. */
  284. function makeMenu($row,&$list){
  285. $list[$row['id']]=$row;
  286. if($row['pid']==0){
  287. return $list;
  288. }
  289. $parent =Db::name("admin_menu")->where(["id"=>$row['pid'],"status"=>1,"is_del"=>0])->field("id,menu_name,menu_img,menu_url,menu_route,pid,is_show,is_private,menu_type,weight")->find();
  290. if($parent==false) return $list;
  291. makeMenu($parent,$list);
  292. }
  293. /**
  294. * 遍历集合处理
  295. * @param $menuArr
  296. */
  297. function MenuTree(&$menuArr,$pid=0){
  298. $meun=[];
  299. foreach ($menuArr as $value){
  300. if($value['pid']==$pid){
  301. if($value['menu_type']==1)$value['child']=MenuTree($menuArr,$value['id']);
  302. $meun[]=$value ;
  303. }
  304. }
  305. return $meun;
  306. };
  307. function upload($files,$extend="xls")
  308. {
  309. // 获取表单上传文件
  310. try {
  311. validate([
  312. 'file' => [
  313. 'fileExt' => 'xlsx,xls'
  314. ]
  315. ],
  316. [
  317. 'file.fileExt' => '不支持的文件',
  318. ]
  319. )->check(['file' => $files]);
  320. if ($extend == 'xlsx') {
  321. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  322. } else {
  323. $objReader = PHPExcel_IOFactory::createReader('Excel5');
  324. }
  325. $savename = Filesystem::disk('public')->putFile('topic/excel', $files);
  326. $import_path = root_path() . 'public/storage/' . $savename;
  327. $spreadsheet = $objReader->load($import_path);
  328. $sheet = $spreadsheet->getActiveSheet();
  329. $sheetData = $sheet->toArray();
  330. if (empty($sheetData) || !is_array($sheetData)) {
  331. return ['code' => 1003, "msg" => '数据不能为空'];
  332. }
  333. return ['code' => 0, "msg" => '数据解析成功', 'data' => $sheetData];
  334. } catch (think\exception\ValidateException $e) {
  335. // echo $e->getMessage();
  336. return ['code' => 1003, "msg" => $e->getMessage()];
  337. }
  338. }
  339. /**
  340. * @param $files
  341. * @return array
  342. */
  343. function UploadImg($files)
  344. {
  345. $savename = [];
  346. $files = !is_array($files) ? [$files] : $files;
  347. try {
  348. //验证
  349. validate(['imgFile' => ['fileSize' => 10240000, 'fileExt' => 'jpg,jpeg,png,bmp,gif', 'fileMime' => 'image/jpeg,image/png,image/gif']])->check(['imgFile' => $files]);
  350. foreach ($files as $file) {
  351. $url = Filesystem::disk('public')->putFile('img/' . date("Ymd"), $file, function () use ($file) {
  352. return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
  353. });
  354. $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
  355. $temp = ["url" =>"storage/".$url, "name" => $name];
  356. $savename[] = $temp;
  357. }
  358. return $savename;
  359. } catch (\think\exception\ValidateException $e) {
  360. return $e->getMessage();
  361. }
  362. }
  363. if(!function_exists("invoiceType")){
  364. //发票类型 1 专用2普通3电子普通4 电子专用 5 q全电子发票
  365. function invoiceType($key=0){
  366. $panda= ['',"004",'007','026','028','000'];
  367. return $panda[$key]??'';
  368. }
  369. }
  370. if(!function_exists('excelExport')){
  371. /**
  372. * @param string $fileName
  373. * @param array $headArr
  374. * @param array $data
  375. * @throws \PHPExcel_Exception
  376. * @throws \PHPExcel_Reader_Exception
  377. * @throws \PHPExcel_Writer_Exception
  378. */
  379. function excelExport($fileName = '', $headArr = [], $data = [])
  380. {
  381. $objPHPExcel = new PHPExcel();
  382. $objPHPExcel->getProperties();
  383. $keyA = 0; // 设置表头
  384. foreach ($headArr as $v) {
  385. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  386. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  387. $keyA += 1;
  388. }
  389. $column = 2;
  390. $objActSheet = $objPHPExcel->getActiveSheet();
  391. foreach ($data as $key => $rows) { // 行写入
  392. $span = 0;
  393. foreach ($rows as $keyName => $value) { // 列写入
  394. //判断数据是否有数组,如果有数组,转换成字符串
  395. if(is_array($value)){
  396. $value = implode("、", $value);
  397. }
  398. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  399. $span++;
  400. }
  401. $column++;
  402. }
  403. // var_dump($objActSheet->getActiveCell());
  404. $fileName .= "_" . date("Y_m_d", time()) . ".xls";
  405. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  406. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  407. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  408. // Redirect output to a client’s web browser (Excel2007)
  409. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  410. header('Content-Disposition: attachment;filename="'.$fileName.'"');
  411. header('Cache-Control: max-age=0');
  412. // If you're serving to IE 9, then the following may be needed
  413. header('Cache-Control: max-age=1');
  414. // If you're serving to IE over SSL, then the following may be needed
  415. header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  416. header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  417. header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  418. header ('Pragma: public'); // HTTP/1.0
  419. // header("Content-Type: application/octet-stream"); # 流文件输出
  420. // header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  421. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  422. $objWriter->save('php://output'); // 文件通过浏览器下载
  423. exit();
  424. }
  425. }
  426. if(!function_exists("Csv_save")){
  427. function Csv_save($fileName,$headArr =[],$data=[],$num=10000){
  428. /*
  429. * 导出数据生成csv文件
  430. * @param file_name string 文件名
  431. * @param headArr array 表头
  432. * @param $db \think\db\Query 使用Db方法后生成的对象实例
  433. * @param callback 回调函数,一般用在对查询结果进行二次处理的时候(例如二次计算,将状态等值由数字转变为文本,额外添加字段等)
  434. */
  435. set_time_limit(0);//让程序一直运行
  436. $fileName .= date('_Y_m_d');//文件名拼接日期
  437. header('Content-Encoding:UTF-8');
  438. header("Content-type:application/vnd.ms-excel;charset=UTF-8");
  439. header('Content-Disposition:attachment;filename="' . $fileName . '.csv"');
  440. $fp = fopen('php://output', 'a');//打开php标准输出流
  441. fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//添加bom头,以UTF-8编码导出的csv文件,如果文件头未添加bom头,打开会出现乱码
  442. try {
  443. if (!empty($headArr)) fputcsv($fp, $headArr);//添加导出标题
  444. $max = PHP_INT_MAX;
  445. $count=0;//阈值
  446. //写入数据
  447. for ($i = 1; $i > 0; $i++) {
  448. $has_data = false;//默认没有查询到数据
  449. foreach ($data as $k => $value) {
  450. // $max = $value[$pk];//维护最大值
  451. // $has_data = true;//存在查询数据
  452. // if ($function) $value = $function($value);//调用回调函数处理
  453. if (empty($headArr)) {
  454. $headArr = array_keys($value);
  455. fputcsv($fp, $headArr);//添加导出标题
  456. }
  457. fputcsv($fp, $value);
  458. if (($k + 1) % $num == 0) {
  459. ob_flush();//清空缓存,释放内存
  460. flush();
  461. }
  462. $count++;//阈值自增
  463. }
  464. if ($has_data === false) break;//结束循环
  465. if($count>=1000000) throw new \think\Exception('超出文件的最大显示行数,请根据条件分批次导出数据或使用预约导出功能,更多问题请联系开发人员');
  466. }
  467. }catch (\think\Exception $exception){
  468. fputcsv($fp,[$exception->getMessage()]);
  469. }
  470. ob_flush();
  471. flush();
  472. ob_end_clean();
  473. fclose($fp);
  474. exit();
  475. }
  476. }
  477. if(!function_exists('menuAction')){
  478. function menuAction($row,&$list=[]){
  479. $temp=[];
  480. foreach ($row as $key=>$value){
  481. if($value['pid']==0){
  482. $list[]=$value;
  483. }else{
  484. $menu=Db::name("admin_menu")->where(["id"=>$value['pid'],"is_del"=>0,"status"=>1])->field("id,menu_name,menu_img,menu_route,menu_url,pid,level,is_show,is_private,menu_type,status")->findOrEmpty();
  485. if(empty($menu)) continue;
  486. if(!isset($temp[$value['pid']]))$temp[$value['pid']]=$menu;
  487. $temp[$value['pid']]['child'][]=$value;
  488. }
  489. }
  490. // $list=$temp;
  491. if (!empty($temp)){
  492. menuAction($temp,$list);
  493. }
  494. }
  495. }
  496. /**
  497. * 批量生成多个文件excel,生成压缩包,保存到本地,返回文件链接
  498. * datas 生成器
  499. * header array 头部字段
  500. * filename string 文件名
  501. */
  502. if (!function_exists('excelSaveFile')) {
  503. function excelSaveFile($datas, string $filename = '')
  504. {
  505. // $urls = [];
  506. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  507. if (!is_dir($dir)) mkdir($dir, 0777, true);
  508. // foreach ($datas as $item) {
  509. PHPExcel_Settings::setCacheStorageMethod();
  510. PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;//单元格缓存为MemoryGZip
  511. $objPHPExcel = new PHPExcel();
  512. $keyA = 0; // 设置表头
  513. $column = 2;
  514. $objActSheet = $objPHPExcel->getActiveSheet();
  515. foreach ($datas as $key => $rows) { // 行写入
  516. //第一行取key作表头
  517. if($key==0){
  518. $objPHPExcel->getProperties();
  519. foreach ($rows as $k=>$v) {
  520. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  521. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $k);
  522. $keyA += 1;
  523. }
  524. }
  525. //写入列
  526. $span = 0;
  527. foreach ($rows as $keyName => $value) {
  528. //判断数据是否有数组,如果有数组,转换成字符串
  529. if (is_array($value)) $value = implode("、", $value);
  530. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  531. $span++;
  532. }
  533. $column++;
  534. }
  535. $file = $filename . ".xls";
  536. $objPHPExcel->setActiveSheetIndex(0);
  537. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  538. $objWriter->save($dir . $file); // 文件通过浏览器下载
  539. $url = $dir . $file;
  540. if (!file_exists($url)) throw new Exception('文件生成失败');
  541. $saveDir = root_path() . "public/storage/zip/" . date('Ymd') . '/';
  542. if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
  543. $file_dir = $saveDir . $filename . ".zip";
  544. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  545. $zip = new \ZipArchive ();
  546. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  547. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  548. # 5.3 批量写入压缩包
  549. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  550. // foreach ($urls as $fileName) {
  551. @$zip->addFile($url, DIRECTORY_SEPARATOR . basename($url));
  552. // }
  553. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  554. # 5.4 关闭压缩包写入
  555. $zip->close();
  556. @deldir($dir);//删除已生成的文件及目录
  557. //6. 检查文件是否存在,并输出文件
  558. if (!file_exists($file_dir)) throw new Exception('压缩包文件不存在');
  559. return str_replace(root_path()."public/" , env("host.host"), $file_dir);
  560. }
  561. }
  562. //读取大文件
  563. if (!function_exists('read_big_file')){
  564. function read_big_file(string $file=''){
  565. $handle = fopen($file, 'rb');
  566. while (feof($handle) === false) {
  567. yield fgets($handle);
  568. }
  569. fclose($handle);
  570. }
  571. }
  572. function deldir($path){
  573. //如果是目录则继续
  574. if(is_dir($path)){
  575. //扫描一个文件夹内的所有文件夹和文件并返回数组
  576. $p = scandir($path);
  577. //如果 $p 中有两个以上的元素则说明当前 $path 不为空
  578. if(count($p)>2){
  579. foreach($p as $val){
  580. //排除目录中的.和..
  581. if($val !="." && $val !=".."){
  582. //如果是目录则递归子目录,继续操作
  583. if(is_dir($path.$val)){
  584. //子目录中操作删除文件夹和文件
  585. deldir($path.$val.'/');
  586. }else{
  587. //如果是文件直接删除
  588. unlink($path.$val);
  589. }
  590. }
  591. }
  592. }
  593. }
  594. //删除目录
  595. return rmdir($path);
  596. }