php 常用的自定义方法(日志记录等)

tech2023-02-03  97

<?php /** * 生成 GUID */ function createGuid() : string { $charId = strtoupper(md5(uniqid(mt_rand(), true))); $hyphen = chr(45); // '-' $guid = substr($charId, 0, 8) . $hyphen . substr($charId, 8, 4) . $hyphen . substr($charId, 12, 4) . $hyphen . substr($charId, 16, 4) . $hyphen . substr($charId, 20, 12); return $guid; } /** * 根据xml节点获取数组 */ function getArray($node) { $array = false; if ($node->hasAttributes()) { foreach ($node->attributes as $attr) { $array[$attr->nodeName] = $attr->nodeValue; } } if ($node->hasChildNodes()) { foreach ($node->childNodes as $childNode) { if ($childNode->nodeType != XML_TEXT_NODE) { $array[$childNode->nodeName][] = getArray($childNode); } } } if($node->nodeValue != ''){ $array[$node->nodeName] = $node->nodeValue; } return $array; } /** * 将xml字符串转换成数组 */ function xml2array(string $xmlstring = '') { try { $dom = new DOMDocument('1.0','utf-8'); $dom->loadXML($xmlstring); $arr = getArray($dom->documentElement); } catch (Exception $e) { $arr = []; } return $arr; } /** * 移除 xml 字符串头 */ function removeXmlHeader(string $xml = '') : string { try { $xml = nl2br($xml); $xml = explode('<br />', $xml); $xml = substr($xml[1], 1); } catch (Exception $e) { $xml = ''; } return $xml; } /** * 把下划线转换成驼峰式 */ function convertUnderline(string $str, bool $ucfirst = false) : string { $str = ucwords(str_replace('_', ' ', $str)); $str = str_replace(' ','',lcfirst($str)); return $ucfirst ? ucfirst($str) : $str; } /** * 下载文件 */ function download($filename, $data = null, $filetype = null) { $basename = pathinfo($filename); if (!$data) { ob_clean(); flush(); $data = file_get_contents($filename); header('Content-Length:' . filesize($filename)); //指定文件大小的 } if ($filetype) { header("Content-Type: $filetype"); //指定下载文件类型的 } // $name = urlencode($basename['basename']); $name = base64_encode($basename['basename']); header('Content-Disposition:attachment;filename=' . $name); echo $data; } /** * * 打包下载多个文件 * 单个文件则不打包 * @param $fileList * @param string $filename 多个文件为 zip 单个为 txt * @return bool */ function downloadFiles($fileList, $filename = "file") { if (count($fileList) < 1) return false; ob_start(); if (count($fileList) > 1) { ob_end_clean(); $files = implode($fileList,' '); $filePath= config("download_path") . 'excel/'.$filename.'.zip'; $zip = "zip -jr $filePath $files"; exec($zip); foreach ($fileList as $file) { unlink($file); } $basename = pathinfo($filePath); ob_clean(); flush(); $data = file_get_contents($filePath); header('Content-Length:' . filesize($filePath)); //指定文件大小的 $name = base64_encode($basename['basename']); header('Content-Disposition:attachment;filename=' . $name); echo $data; unlink($filePath);exit(); } else { $pos = strrpos($filename,'.'); if (!$pos) { $fileInfo = pathinfo($fileList[0]); $ext = $fileInfo["extension"]; $filename .= '.'.$ext; } else { $filename .= '.txt'; } $data = file_get_contents($fileList[0]); } ob_end_clean(); download($filename, $data); foreach ($fileList as $file) { unlink($file); } } /** * 返回指定单位的时间数据 */ function time2Unit($time, $unit = 'seconds') { if ($unit == 'minutes') return floor($time / 60); if ($unit == 'hours') return floor($time / (60 * 60)); if ($unit == 'days') return floor($time / (60 * 60 * 24)); if ($unit == 'months') return floor($time / (60 * 60 * 24 * 31)); if ($unit == 'years') return floor($time / (60 * 60 * 24 * 365)); if ($unit == 'weeks') return floor($time / (60 * 60 * 24 * 7)); return $time; } /** * 文件导出 */ function exportFile($filename, $headerTitle, $formatData, $type) { try { array_unshift($formatData, $headerTitle); switch($type) { case 'xlsx': return exportFileXlsx($filename . '.xlsx', $formatData); case 'html': return exportFileHtml($filename . '.html', $formatData); case 'pdf': return exportFilePdf($filename . '.pdf', $formatData); } } catch(\Exception $e) { return 0; } } /** * 获取Excel格子编号 * $isrow 是否获取行编号,否则获取列编号 * A1 B1 C1 ... AA1 ... * A2 B2 C2 ... AA2 ... * ... */ function getExcelNextCellID($isrow = true, $curId = null, $newline = false) { $match = []; if (is_null($curId) || !\preg_match("/^([A-Z]+)(\d+)$/", $curId, $match)) return 'A1'; $alphaIncr = false; // 字母+1 $numIncr = false; // 数字+1 if ($isrow) { $alphaIncr = true; } else { $numIncr = true; } if ($newline) { $alphaIncr = false; $numIncr = true; $match[1] = 'A'; } if ($alphaIncr) { $len = strlen($match[1]); for($i = $len - 1; $i >= 0; $i--) { if ($match[1][$i] < 'Z') { $match[1][$i] = \chr(\ord($match[1][$i]) + 1); break; } else { $match[1][$i] = 'A'; // 需进位 if ($i == 0) { $match[1] = 'A' . $match[1]; } } } } if ($numIncr) { $match[2]++; } return $match[1] . $match[2]; } /** * 导出Excel,可导出多个sheet */ function makeExportFileXlsxSubContent ($filename, &$fileWriter, $formatData, &$nextRowIdx = 0) { if (!$fileWriter) { $fileWriter = new \PHPExcel(); $fileWriter->getProperties()->setCreator("Venustech") ->setLastModifiedBy("Venustech") ->setTitle($filename); } $sheet = $fileWriter->setActiveSheetIndex(0); $rowIdx = $nextRowIdx ? $nextRowIdx : 0; foreach($formatData as $rowData) { foreach($rowData as $colInx => $value) { // $sheet->setCellValue($cellid, $value); $sheet->setCellValueByColumnAndRow($colInx, $rowIdx, $value); } $rowIdx++; } $nextRowIdx = $rowIdx; } function exportFileXlsx($filename, $formatData, $isPdf = false) { $objPHPExcel = new \PHPExcel(); $objPHPExcel->getProperties()->setCreator("Venustech") ->setLastModifiedBy("Venustech") ->setTitle($filename); // ->setSubject("subject") // ->setDescription("Description") // ->setKeywords("Keywords") // ->setCategory("Category"); if (\array_key_exists('WorkSheet', $formatData)) { // 需要制作多个sheet foreach ($formatData['WorkSheet'] as $index => $workSheet) { if ($index != 0) { $objPHPExcel->createSheet(); } $sheet = $objPHPExcel->setActiveSheetIndex($index); $cellid = getExcelNextCellID(); foreach($workSheet['data'] as $idx =>$rowData) { foreach($rowData as $value) { $sheet->setCellValue($cellid, $value); if (!$idx) { \preg_match("/([A-Z]+)/", $cellid, $match); $sheet->getColumnDimension($match[0])->setWidth(24); } $cellid = getExcelNextCellID(true, $cellid); } $cellid = getExcelNextCellID(false, $cellid, true); } if (\array_key_exists('name', $workSheet) && $workSheet['name']) { $objPHPExcel->getActiveSheet()->setTitle($workSheet['name']); } else { $objPHPExcel->getActiveSheet()->setTitle('WorkSheet' . $index); } } $objPHPExcel->setActiveSheetIndex(0); // 设置第一个sheet为工作sheet } else { $sheet = $objPHPExcel->setActiveSheetIndex(0); $cellid = getExcelNextCellID(); foreach($formatData as $idx =>$rowData) { foreach($rowData as $value) { $sheet->setCellValue($cellid, $value); if (!$idx) { \preg_match("/([A-Z]+)/", $cellid, $match); $sheet->getColumnDimension($match[0])->setWidth(24); } $cellid = getExcelNextCellID(true, $cellid); } $cellid = getExcelNextCellID(false, $cellid, true); } // $objPHPExcel->getActiveSheet()->setTitle('Simple'); } if ($isPdf) { header('Content-Type: application/pdf'); $rendererName = PHPExcel_Settings::PDF_RENDERER_TCPDF; $rendererLibrary = 'tcpdf'; $rendererLibraryPath = dirname(__FILE__).'/../vendor/tecnick.com/' . $rendererLibrary; if (!\PHPExcel_Settings::setPdfRenderer( $rendererName, $rendererLibraryPath )) { throw("NOTICE: Please set the valid values : $rendererName and $rendererLibraryPath"); } // $objPHPExcel->getActiveSheet()->setShowGridLines(false); $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF'); $objWriter->SetFont('stsongstdlight', '', 20); // $objWriter->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); // $objWriter->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); } else { header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); // xls $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); // xlsx } header("Content-Disposition: attachment;filename=" . \base64_encode($filename)); // header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed // header('Cache-Control: max-age=1'); $objWriter->save('php://output'); exit; } /** * 根据数据 * 组织成HTML */ function makeExportFileHtmlContent($formatData) { $rowStr = ''; foreach($formatData as &$rowData) { if ($rowStr) $rowStr .= ", "; foreach ($rowData as &$d) $d = preg_replace('/\r\n|\n/', '<br />', (\addslashes($d))); $rowStr .= ("['" . \implode("', '", $rowData) . "']"); } $templateStr = "<script>var data = [$rowStr]</script>\n"; $templateData = \file_get_contents(ROOT_PATH . 'download/import_data_template.html'); $totalData = $templateStr . $templateData; return $totalData; } /** * 分多次写入,导出文件 * type: start middle end start_end */ function makeExportFileHtmlSubContent($formatData, $type = 'middle') { $header = '<tr>'; $logTitle = ''; $totalTitle = ''; if (isset($formatData[0]) && !empty($formatData[0])) { foreach($formatData[0] as $key => $rowData) { if ($key == 0) { $logTitle = $rowData; } elseif ($key == 1) { $totalTitle = $rowData; } else { $header .= "<th>".$rowData."</th>"; } } $header .= '</tr>'; } array_shift($formatData); $body = '<tr>'; foreach($formatData as $key => $rowData) { array_unshift($rowData,$key+1); foreach ($rowData as $value) { $body .= "<td><a>".$value."</a></td>"; } $body .= '<tr>'; } $count = $formatData ? count($formatData) : 0; return '<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title id="title">'.$logTitle.'</title> </head> <style type="text/css"> *{margin: 0;padding: 0;} body { padding: 40px 100px; } .demo { width: 600px; margin: 40px auto; font-family: \'trebuchet MS\', \'Lucida sans\', Arial; font-size: 14px; color: #444; } table { *border-collapse: collapse; /* IE7 and lower */ border-spacing: 0; width: 100%; } .bordered { border: solid #ccc 1px; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 0 1px 1px #ccc; -moz-box-shadow: 0 1px 1px #ccc; box-shadow: 0 1px 1px #ccc; } .bordered tr { -o-transition: all 0.1s ease-in-out; -webkit-transition: all 0.1s ease-in-out; -moz-transition: all 0.1s ease-in-out; -ms-transition: all 0.1s ease-in-out; transition: all 0.1s ease-in-out; } .bordered .highlight, .bordered tr:hover { background: #df6f6fef; } .bordered td, .bordered th { border-left: 1px solid #ccc; border-top: 1px solid #ccc; padding: 10px; text-align: left; } .bordered th { text-align: left; background-color: #dcedf9; background-image: -webkit-gradient(linear, left top, left bottom, from(#ebf3fc), to(#dce9f9)); background-image: -webkit-linear-gradient(top, #ebf3fc, #dce9f9); background-image: -moz-linear-gradient(top, #ebf3fc, #dce9f9); background-image: -ms-linear-gradient(top, #ebf3fc, #dce9f9); background-image: -o-linear-gradient(top, #ebf3fc, #dce9f9); background-image: linear-gradient(top, #ebf3fc, #dce9f9); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#ebf3fc, endColorstr=#dce9f9); -ms-filter: "progid:DXImageTransform.Microsoft.gradient (GradientType=0, startColorstr=#ebf3fc, endColorstr=#dce9f9)"; -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset; -moz-box-shadow:0 1px 0 rgba(255,255,255,.8) inset; box-shadow: 0 1px 0 rgba(255,255,255,.8) inset; border-top: none; text-shadow: 0 1px 0 rgba(255,255,255,.5); } .bordered td:first-child, .bordered th:first-child { border-left: none; } .bordered th:first-child { -moz-border-radius: 6px 0 0 0; -webkit-border-radius: 6px 0 0 0; border-radius: 6px 0 0 0; } .bordered th:last-child { -moz-border-radius: 0 6px 0 0; -webkit-border-radius: 0 6px 0 0; border-radius: 0 6px 0 0; } .bordered tr:last-child td:first-child { -moz-border-radius: 0 0 0 6px; -webkit-border-radius: 0 0 0 6px; border-radius: 0 0 0 6px; } .bordered tr:last-child td:last-child { -moz-border-radius: 0 0 6px 0; -webkit-border-radius: 0 0 6px 0; border-radius: 0 0 6px 0; } a { color: #000000; text-decoration: none; } </style> <body> <div><span id="totalTitle">'.$totalTitle.':</span><span id="totalnum">'.$count.'</span> </div> <table class="bordered"> <thead> <tr id="header">'.$header.'</tr> </thead> <tbody id="content">'.$body.'</tbody> </table> </body> </html>'; } /** * 导出html */ function exportFileHtml($filename, $formatData) { $totalData = makeExportFileHtmlContent($formatData); header('Content-Type: text/webviewhtml'); header("Content-Disposition: attachment;filename=" . \base64_encode($filename)); echo $totalData; } /** * 导出pdf */ function exportFilePdf($filename, $formatData) { $totalData = '<table style="width:100%;"><thead><tr>'; // makeExportFileHtmlContent($formatData); $header = ''; foreach($formatData[0] as $value) { $header .= ("<td>$value</td>"); } $totalData .= $header . '</tr></thead><tbody>'; $body = ''; foreach($formatData as $idx => $rowData) { if (!$idx) continue; $body .= ("<tr>"); foreach($rowData as $value) { $body .= ("<td>$value</td>"); } $body .= ("</tr>"); } $totalData .= $body . '</tbody></table>'; $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $pdf->SetCreator("Venustech"); $pdf->SetAuthor("Venustech"); $pdf->SetTitle($filename); // $pdf->SetSubject('TCPDF Tutorial'); // $pdf->SetKeywords('TCPDF, PDF, example, test, guide'); $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); // set auto page breaks // set text shadow effect $pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal')); $pdf->AddPage(); $pdf->writeHTMLCell(0, 0, '', '', $totalData, 0, 1, 0, true, '', true); // 死循环了 // header('Content-Type: application/pdf'); // header("Content-Disposition: attachment;filename=" . \base64_encode($filename)); $data = $pdf->Output(\base64_encode($filename), 'I'); // echo $data; // exit; } function genMixCode($size = 6) { $codeString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $maxNum = strlen($codeString) - 1; $newPass = ''; for ($i = 0; $i < $size; $i++) { $idx = \rand(0, $maxNum); $newPass = $newPass . substr($codeString, $idx, 1); } return $newPass; } /** * 转义字符串 * ' " \ : / */ function addslashesCustom($str) { $str = \addcslashes($str, '-\'\":/\ ()[]{}*^?!~'); return $str; } function importExcel($file, $type) { try { // 判断文件是否存在 if (!\file_exists($file)) { Log::debug('<<<<< import excel failed,not exist,filename=' . $file); return false; } // ini_set('max_execution_time', '0'); // Vendor('PHPExcel.PHPExcel'); $objReader = PHPExcel_IOFactory::createReader($type); // 判断使用哪种格式 $objReader->setReadDataOnly(true); // 只读取数据,会智能忽略所有空白行 $objPHPExcel = $objReader->load($file); // 加载Excel文件 $sheetCount = $objPHPExcel->getSheetCount(); // 获取sheet工作表总个数 $rowData = []; $RowNum = 0; /* 读取表格数据 */ for ($i = 0; $i <= $sheetCount - 1; $i++) { // 循环sheet工作表的总个数 $sheet = $objPHPExcel->getSheet($i); $highestRow = $sheet->getHighestRow(); $RowNum += $highestRow - 1; // 计算所有sheet的总行数 $highestColumn = $sheet->getHighestColumn(); // 从第$i个sheet的第1行开始获取数据 for ($row = 1; $row <= $highestRow; $row++) { // 把每个sheet作为一个新的数组元素 键名以sheet的索引命名 利于后期数组的提取 $rowData[$i][] = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE); } } /*删除每行表头数据*/ // foreach ($rowData as $k => $v) { // array_shift($rowData[$k]); // } } catch (\Exception $e) { \think\Log::info('import excel error: ' . ($e->xdebug_message ? $e->xdebug_message : $e->message)); return false; } return ['rowNum' => $RowNum, "excelData" => $rowData]; } /** * 判断IP格式 */ function validateIP($ip, $type) { if ($type === 1) return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); // 合法的IPv4 else if ($type === 2) return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE); // 合法的公共IPv4 192.168.1.1这类的私有IP地址将会排除在外 else if ($type === 3) return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE); // 合法的IPv6 else if ($type === 4) return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE); // 合法的IPv4/6 else return filter_var($ip, FILTER_VALIDATE_IP); // 合法的IP } /** * 格式化通用时间格式 */ function formatTime($time, $format = 'Y-m-d H:i:s') { $fmtTime = \date($format, strtotime($time)); return $fmtTime ? $fmtTime : ''; } /** * 将多维对象全部转换成数组 */ function objectToArray($obj){ $arr = []; $_arr = is_object($obj) ? get_object_vars($obj) :$obj; foreach ($_arr as $key=>$val) { $val = (is_array($val) || is_object($val)) ? objectToArray($val):$val; $arr[$key] = $val; } return $arr; } /** * std to array * @param $array * @return array */ function stdClassToArray($array) { if(is_object($array)) { $array = (array)$array; } if(is_array($array)) { foreach($array as $key=>$value) { $array[$key] = stdClassToArray($value); } } return $array; } /** * 记录日志 年月/日/日志等级/日_日志等级.log * @param $level string 日志等级 * @param $msg string 日志信息 * @return bool */ function logMessage($level, $msg) { $level = strtolower($level); $msg = is_array($msg) || is_object($msg) ? json_encode($msg) : $msg; $webLog = config('web_log'); $logLevel = $webLog["level"]; $logTime = $webLog["time"]; $logPath = $webLog["path"]; // 支持的错误类型 if (!in_array($level, $logLevel)) { return false; } // 删除有效期外的日志 $delDir = $logPath . date("Ym", strtotime("-$logTime day")) . DS . date("d", strtotime("-$logTime day")) . DS; if (is_dir($delDir)) { delDir($delDir); } // 文件夹目录 $folder = $logPath . date('Ym', time()) . DS . date('d', time()) . DS . $level . DS; if (!file_exists($folder)) { Directory($folder); } $info = array( 'REMOTE_ADDR' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', 'REQUEST_METHOD' => isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '', 'REQUEST_URI' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', ); $info = implode(' --> ', $info); $file = date('H') . '_hours_' . $level . '.log'; $txt = '---------------------------------------------------------------' . "\n"; $content = $txt . '[ ' . date('Y-m-d H:i:s ') . '] ' . $info . "\n" . '[ ' . $level . ' ]:' . $msg . "\n"; $path = $folder . $file; if (!file_put_contents($path, $content, FILE_APPEND)) { logMessage('fatal', ' 写入日志失败:' . $content); } } /** * 递归创建文件 * @param $dir * @return bool */ function Directory($dir){ if(is_dir($dir) || @mkdir($dir,0777,true)){ return true; }else{ $dirArr = explode('/',$dir); array_pop($dirArr); $newDir = implode('/',$dirArr); Directory($newDir); if(@mkdir($dir , 0777,true)){ return true; } } } /** * 获取当前浏览器型号 * @return mixed|string */ function getBrowse() { $browse = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ""; if(preg_match('/360SE/', $browse)){ $browse = "360se"; } elseif (preg_match('/Maxthon/', $browse)){ $browse = "maxthon"; } elseif (preg_match('/Tencent/', $browse)){ $browse = "tencent"; } elseif (preg_match('/Green/', $browse)){ $browse = "green"; } elseif (preg_match('/baidu/', $browse)){ $browse = "baidu"; } elseif (preg_match('/TheWorld/', $browse)){ $browse = "tw"; } elseif (preg_match('/MetaSr/', $browse)){ $browse = "sogou"; } elseif (preg_match('/Firefox/', $browse)){ $browse = "firefox"; } elseif (preg_match('/MSIE\s6\.0/', $browse)){ $browse = "ie"; } elseif (preg_match('/MSIE\s7\.0/', $browse)){ $browse = "ie"; } elseif (preg_match('/MSIE\s8\.0/', $browse)){ $browse = "ie"; } elseif (preg_match('/MSIE\s9\.0/', $browse)) { $browse = "ie"; } elseif (preg_match('/Netscape/', $browse)){ $browse = "netscape"; } elseif (preg_match('/Opera/', $browse)){ $browse = "opera"; } elseif (preg_match('/Chrome/', $browse)){ $browse = "chrome"; } elseif (preg_match('/Gecko/', $browse)){ $browse = "gecko"; } elseif (preg_match('/Safari/', $browse)){ $browse = "safari"; } else{ $browse = "unknow"; } return $browse; } /** * 删除文件夹及文件夹下所有的文件 * @param $dir * @return bool */ function delDir($dir) { //先删除目录下的文件: if(!is_dir($dir)) { if (unlink($dir)) { return true; } else { return false; } } else { $dh = opendir($dir); while ($file=readdir($dh)) { if($file != "." && $file != "..") { $fullpath=$dir . "/" . $file; chmod($fullpath,0755); if(!is_dir($fullpath)) { unlink($fullpath); } else { delDir($fullpath); } } } closedir($dh); //删除当前文件夹: if(rmdir($dir)) { return true; } else { return false; } } } /** * 判断目录是否为空目录 * @param $dir_path * @return bool */ function isEmptyDir($dir_path) { $isEmpty = true; if (!is_dir($dir_path)){ $isEmpty = true; } else { $dir = opendir($dir_path); while ($file = readdir($dir)){ if($file == "." || $file == "..") continue; $isEmpty = false; break; } closedir($dir); } return $isEmpty; } /** * 以GET请求模拟访问 * @param string $url 访问URL * @param array $query GET数 * @param array $options * @return bool|string * @throws /Exception */ function curlGet($url = "", $query = [], $options = []) { $options['query'] = $query; return doRequest('get', $url, $options); } /** * 以post访问模拟访问 * @param string $url 访问URL * @param array $data POST数据 * @param array $options * @return bool|string * @throws /Exception */ function curlPost($url = "", $data = [], $options = []) { $options['data'] = $data; return doRequest('post', $url, $options); } /** * CURL模拟网络请求 * @param string $method 请求方法 * @param string $url 请求方法 * @param array $options 请求参数[headers,data,ssl_cer,ssl_key] * @return bool|string * @throws /Exception */ function doRequest($method, $url, $options = []) { $curl = curl_init(); // GET参数设置 if (!empty($options['query'])) { $url .= (stripos($url, '?') !== false ? '&' : '?') . http_build_query($options['query']); } // CURL头信息设置 if (!empty($options['headers'])) { curl_setopt($curl, CURLOPT_HTTPHEADER, $options['headers']); } // POST数据设置 if (strtolower($method) === 'post') { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $options['data']); } // 证书文件设置 if (!empty($options['ssl_cer'])) { if (file_exists($options['ssl_cer'])) { curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM'); curl_setopt($curl, CURLOPT_SSLCERT, $options['ssl_cer']); } else { throw new \Exception("Certificate files that do not exist. --- [ssl_cer]"); } } // 证书文件设置 if (!empty($options['ssl_key'])) { if (file_exists($options['ssl_key'])) { curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM'); curl_setopt($curl, CURLOPT_SSLKEY, $options['ssl_key']); } else { throw new \Exception("Certificate files that do not exist. --- [ssl_key]"); } } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_TIMEOUT, 60); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)]; return (intval($status["http_code"]) === 200) ? $content : false; } /** * 格式化输出 * @param $data */ function dd($data) { echo "<pre>"; var_dump($data); echo "</pre>"; die; } /** * 格式化异步请求返回结果 * @param array $data 返回的数据 * @param string $msg 提示信息 * @param int $status 状态码;0:failure,1:success */ function returnJson($data = [], string $msg = '', int $status = 1) { echo json_encode([ "data" => $data, "msg" => $msg, "result" => $status, ]); exit(); } /** * 转化 URL 参数 * @param array $data * @return string */ function setHttpQuery($data = []) { $str = ""; if ($data) { foreach ($data as $k => $v) { $str .= $k . '=' . $v . '&'; } } return rtrim($str, '&'); } /** * 格式化异步请求返回结果 * @param array $data 返回的数据 * @param string $msg 提示信息 * @param int $code 状态码;0:success,1:failure * @param int $httpCode http 状态码 * @param array $header header 头 * @param array $options * @return \think\response\Json */ function show(array $data = [], string $msg = 'success', int $code = 0, int $httpCode = 200, array $header = [], array $options = []) { $return = [ "results" => $data, "status_text" => $msg, "status_code" => $code, ]; return json($return, $httpCode, $header, $options); } /** * 返回 api 格式 * @param string $key * @param array $data */ function returnApiJson(array $data = [], string $key = "master") { $arr = [ "data" => $data[0], "msg" => $data[1], "result" => $data[2], ]; switch ($key) { case "master" : $arr = [ "data" => $data[0], "msg" => $data[1], "result" => $data[2], ]; break; case "projectA" : $arr = [ "results" => $data[0], "status_text" => $data[1], "status_code" => $data[2], ]; break; default: $arr; break; } echo json_encode($arr); exit(); } /** * 通过 IP 掩码 获取ip * @param string $ipString IP 掩码:192.168.1.12/24 * @return array */ function ipParse($ipString = "") { $len = 32; if (strpos($ipString, "/") > 0) { list($ipString, $len) = explode("/", $ipString); } $ip = ip2long($ipString); $mark = 0xFFFFFFFF << (32 - $len) & 0xFFFFFFFF; $ipStart = $ip & $mark; $ipEnd = $ip | (~$mark) & 0xFFFFFFFF; return [ "ip" => long2ip($ip), "mark" => long2ip($mark), "ipStart" => long2ip($ipStart), "ipEnd" => long2ip($ipEnd) ]; // var_dump(ipParse("192.168.1.12/24")); // ["ip"]=> // string(12) "192.168.1.12" // ["mark"]=> // string(13) "255.255.255.0" // ["ipStart"]=> // string(11) "192.168.1.0" // ["ipEnd"]=> // string(13) "192.168.1.255" } /** * 检测当前Ip 是否 在Ip掩码内 * @param string $ip 当前Ip 192.168.1.12 * @param string $ipString Ip掩码 192.168.1.12/24 * @return bool */ function ipIn($ip = "", $ipString = "") { $len = 32; if (strpos($ipString, "/") > 0) { list($ipString, $len) = explode("/", $ipString); } $rightLen = 32 - $len; $bool = ip2long($ip) >> $rightLen == ip2long($ipString) >> $rightLen; if ($bool) { return true; } else { return false; } // var_dump(ipIn("192.168.1.12","192.168.1.12/24")); // bool(true) }

 

最新回复(0)