| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629 |
- <?php
- use lwmf\base\Logger;
- class Helper
- {
- const PARAM_KEY_TYPE = [
- 'string' => 'string', // 字符串
- 'int' => 'int', // 数字
- 'float' => 'float', // float数字
- 'date' => 'date', // 日期
- 'datetime' => 'datetime', // 日期时间
- 'array_string' => 'array_string', // 包含字符串的数组
- 'array_float' => 'array_float', // 包含float的数组
- 'array_int' => 'array_int', // 包含int的数组
- ];
- /**
- * 检查字符串中是否含有任何一个子串
- * @param $str
- * @param array $arr
- * @param bool $case 是否区分大小写 0-否
- * @return bool
- */
- public static function hasAnyString($str, array $arr, bool $case = false): bool
- {
- foreach ($arr as $v) {
- if (!$case && stripos($str, $v) !== false) {
- return true;
- } elseif ($case && str_contains($str, $v)) {
- return true;
- }
- }
- return false;
- }
- /**
- * 获取图片完整路径
- * @param $imageUrl
- * @param string $default
- *
- * @return string
- * @author lizhi <1458705589@qq.com>
- * @date 2021/5/11
- */
- public static function getImageUrl($imageUrl, string $default = '', $params = []): string
- {
- if (empty($imageUrl)) {
- return $default;
- }
- if (str_contains($imageUrl, 'http')) {
- return $imageUrl;
- }
- $imageUrl = IMAGEDOMAIN . '/' . ltrim($imageUrl, '/');
- if (self::getArrParam($params, 'from_type', 'string') == 'console') {
- // 把后端用到图片的地方,加个后缀,类似!max200 !width600这种
- $imageUrl .= '!max200';
- }
- return $imageUrl;
- }
- /**
- * 格式化处理 imgs 字段
- * @param string|null $data
- * @param string $separator
- * @return array
- */
- public static function formatImgFiled(?string $data, string $separator = ','): array
- {
- if (!$data) {
- return [];
- }
- $data = array_filter(explode($separator, $data));
- return array_map(function ($img) {
- return Helper::getImageUrl($img);
- }, $data);
- }
- public static function time_tran($time)
- {
- $text = '请选择正确的时间!';
- if(!$time){
- return $text;
- }
- $current = time();
- $t = $current - $time;
- $retArr = array('刚刚','秒前','分钟前','小时前','天前','月前','年前');
- switch($t){
- case $t < 0://时间大于当前时间,返回格式化时间
- $text = date('Y-m-d',$time);
- break;
- case $t == 0://刚刚
- $text = $retArr[0];
- break;
- case $t < 60:// 几秒前
- $text = $t.$retArr[1];
- break;
- case $t < 3600://几分钟前
- $text = floor($t / 60).$retArr[2];
- break;
- case $t < 86400://几小时前
- $text = floor($t / 3600).$retArr[3];
- break;
- case $t < 2592000: //几天前
- $text = floor($t / 86400).$retArr[4];
- break;
- case $t < 31536000: //几个月前
- $text = floor($t / 2592000).$retArr[5];
- break;
- default : //几年前
- $text = floor($t / 31536000).$retArr[6];
- }
- return $text;
- }
- /**
- * 检查数组是否指定键都存在 true-都在
- * - checkEmptyKey(['num' => 1], ['num']) => true
- * - checkEmptyKey(['num' => 1], ['id']) => false
- * - checkEmptyKey(['num' => 0], ['num']) => false
- * - checkEmptyKey(['num' => 0], ['num'], ['num') => true
- *
- * @param array $data
- * @param $keys
- * @param array $allowEmpty 允许为空的字段
- *
- * @return bool true-通过检查
- * @author lizhi <1458705589@qq.com>
- * @date 2021/6/18
- */
- public static function checkEmptyKey($data, $keys, array $allowEmpty = [])
- {
- if (is_array($keys)) {
- foreach ($keys as $item) {
- if (!isset($data[$item]) || (!in_array($item, $allowEmpty) && empty($data[$item]))) {
- return false;
- }
- }
- } elseif (!isset($data[$keys]) || (!in_array($keys, $allowEmpty) && empty($data[$keys]))) {
- return false;
- }
- return true;
- }
- public static function getPostString($key, $default = null)
- {
- return self::getArrParam($_POST, $key, 'string', $default);
- }
- public static function getPostFloat($key, $default = null)
- {
- return self::getArrParam($_POST, $key, 'float', $default);
- }
- public static function getGetFloat($key, $default = null)
- {
- return self::getArrParam($_GET, $key, 'float', $default);
- }
- public static function isPhone(?string $phone)
- {
- return $phone && preg_match('/^1[3456789]\d{9}$/', $phone);
- }
- public static function getPostInt($key, $default = 0)
- {
- return self::getArrParam($_POST, $key, 'int', $default);
- }
- public static function getGetString($key, $default = null)
- {
- return self::getArrParam($_GET, $key, 'string', $default);
- }
- public static function getGetDate($key, $default = null)
- {
- return self::getArrParam($_GET, $key, 'date', $default);
- }
- public static function getPostDatetime($key, $default = null)
- {
- return self::getArrParam($_POST, $key, 'datetime', $default);
- }
- public static function getGetDatetime($key, $default = null)
- {
- return self::getArrParam($_GET, $key, 'datetime', $default);
- }
- public static function getPostDate($key, $default = null)
- {
- return self::getArrParam($_POST, $key, 'date', $default);
- }
- public static function getGetInt($key, $default = 0)
- {
- return self::getArrParam($_GET, $key, 'int', $default);
- }
- /**
- * 从数组中获取字段
- */
- public static function getArrParam($arr, $name, $type = 'string', $default = null)
- {
- if (isset($arr[$name])) {
- $param = $arr[$name];
- return self::formatByType($param, $type, $default);
- }
- return $default;
- }
- /**
- * @param string $name 从数组中获取字段,并进行安全处理 多维数组示例 area.name
- * @see self::formatByType()
- */
- public static function getByKey($arr, $name, $type = '', $default = null)
- {
- $nameArr = array_filter(explode('.', $name));
- if (count($nameArr) == 1) {
- if (!isset($arr[$name])) {
- return $default;
- } else {
- $param = $arr[$name];
- }
- } else if (count($nameArr) == 2) {
- if (!isset($arr[$nameArr[0]][$nameArr[1]])) {
- return $default;
- } else {
- $param = $arr[$nameArr[0]][$nameArr[1]];
- }
- } else {
- return $default;
- }
- return self::formatByType($param, $type, $default);
- }
- /**
- * 格式化数据
- * @param mixed $param
- * @param string $type 数据类型,将元素处理成这样的数据类型
- - string 字符串
- - int 数字
- - float float数字
- - date 日期
- - datetime 日期时间
- - array_string 包含字符串的数组
- - array_float 包含float的数组
- - array_int 包含int的数组
- * @param mixed $default
- * @return mixed
- */
- public static function formatByType($param, $type, $default)
- {
- if ($type == 'string') {
- $param = addslashes(trim($param));
- }
- elseif ($type == 'int') {
- $param = intval($param);
- }
- elseif ($type == 'float') {
- $param = floatval($param);
- }
- elseif ($type == 'date') {
- if (!empty($param)) {
- $param = date('Y-m-d', strtotime($param));
- } else {
- $param = $default;
- }
- }
- elseif ($type == 'datetime') {
- if (!empty($param)) {
- $param = date('Y-m-d H:i:s', strtotime($param));
- } else {
- $param = $default;
- }
- }
- elseif ($type == 'array_string') {
- if (!empty($param)) {
- foreach ($param as $key => &$item) {
- $item = addslashes(trim($item));
- }
- }
- }
- elseif ($type == 'array_float') {
- if (!empty($param)) {
- foreach ($param as $key => &$item) {
- $item = floatval($item);
- }
- }
- }
- elseif ($type == 'array_int') {
- if (!empty($param)) {
- foreach ($param as $key => &$item) {
- $item = intval($item);
- }
- }
- }
- return $param;
- }
- /**
- * 获取date格式的日期间隔
- */
- public static function intervalDays($date1, $date2)
- {
- $d = @(strtotime($date2) - strtotime($date1)) / (3600 * 24);
- return $d;
- }
- /**
- * 获取一个对象中的某个字段,返回数组
- * @param array $arr 通过查询返回的数组
- * @param string $column 字段名
- */
- public static function getObjectColumn(array $arr, $column = 'id')
- {
- $ret = [];
- if (!empty($arr)) {
- foreach ($arr as $key => $item) {
- $attributes = $item->attributes;
- isset($attributes[$column]) && $ret[] = $attributes[$column];
- }
- }
- return $ret;
- }
- public static function concatArray($arr1, $arr2)
- {
- foreach ($arr2 as $item) {
- if (!in_array($item, $arr1)) {
- $arr1[] = $item;
- }
- }
- return $arr1;
- }
- public static function toJson($code = 200, $data = [], $msg = '请求成功')
- {
- @header("Content-Type: text/json; charset=UTF-8");
- echo json_encode([
- 'code' => $code,
- 'msg' => $msg,
- 'data' => $data
- ]);
- \Yii::app()->end();
- }
- public static function error($msg, $code = 400, $data = [])
- {
- self::toJson($code, $data, $msg);
- }
- public static function ok($data = [], $msg = '操作成功', $code = 200)
- {
- self::toJson($code, $data, $msg);
- }
- public static function success($data = [], $msg = '操作成功', $code = 200)
- {
- self::toJson($code, $data, $msg);
- }
- public static function commonError($_msg = '', $_code = 500, $_data = [])
- {
- return self::commonReturn($_data, $_msg, $_code);
- }
- public static function commonReturn($_data = [], $_msg = '', $_code = 200)
- {
- return [
- 'code' => $_code,
- 'msg' => $_msg,
- 'data' => $_data
- ];
- }
- public static function dealCommonResult($res, $exit = true)
- {
- if ($exit || $res['code'] != 200) {
- Helper::toJson($res['code'], $res['data'], $res['msg']);
- }
- }
- public static function getRandomString($length = 20)
- {
- $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- $str = "";
- for ($i = 0; $i < $length; $i++) {
- $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
- }
- return $str;
- }
- //php防注入和XSS攻击通用过滤
- public static function safeFilter (&$arr)
- {
- $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/'
- ,'/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/'
- ,'/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/',
- '/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/'
- ,'/onmouseout/','/onmouseover/','/onmouseup/','/onunload/');
- if (is_array($arr))
- {
- foreach ($arr as $key => $value)
- {
- if (!is_array($value))
- {
- if (!get_magic_quotes_gpc()) //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
- {
- $value = addslashes($value); //给单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)
- #加上反斜线转义
- }
- $value = preg_replace($ra,'',$value); //删除非打印字符,粗暴式过滤xss可疑字符串
- // $arr[$key] = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
- }
- else
- {
- self::SafeFilter($arr[$key]);
- }
- }
- }
- return $arr;
- }
- public static function getSign($data)
- {
- return md5($data . "145709480B89EE59E3F4D43A56C355F2");
- }
- /**
- * 将二维数组转化为对象数组
- * @param array $arr
- * @return array
- */
- public static function arrayToObjects(array $arr)
- {
- $ret = [];
- foreach ($arr as $item) {
- $ret[] = (object)$item;
- }
- return $ret;
- }
- /**
- * 异步批量get请求
- *
- * @param array $nodes 格式: 'key' => ['url', 'data'] key是标识key,url是请求host,data是post传递的数据
- * @param integer $timeOut 超时时间
- * @return void
- */
- public static function multiGet($nodes, $options = [] ,$timeOut = 5)
- {
- $mh = curl_multi_init();
- $curl_arr = [];
- // 将请求放入curl中
- foreach ($nodes as $key => $node) {
- if (!is_array($node)) {
- continue;
- }
- $ch = curl_init();
- $url = $node['url'] . (strpos($node['url'], '?') === FALSE ? '?' : '');
- if (isset($node['data'])) {
- $url .= http_build_query($node['data']);
- }
- curl_setopt($ch, CURLOPT_URL, $url);
- // 其他的参数按照 function GET($url, $get = array(), array $options = array()) 来
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
- curl_setopt($ch, CURLOPT_TIMEOUT, 15);
- curl_setopt($ch, CURLOPT_SSLVERSION, 1);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // 超时时间
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeOut);
- foreach ($options as $k => $v) {
- curl_setopt($ch, $k, $v);
- }
- $curl_arr[$key] = $ch;
- curl_multi_add_handle($mh, $curl_arr[$key]);
- }
- // 发送请求
- $running = null;
- do {
- usleep(10000);
- curl_multi_exec($mh, $running);
- } while ($running > 0);
- // 获取请求数据,并删除请求
- $ret = [];
- foreach ($nodes as $key => $node) {
- $ret[$key] = curl_multi_getcontent($curl_arr[$key]);
- curl_multi_remove_handle($mh, $curl_arr[$key]);
- }
- curl_multi_close($mh);
- return $ret;
- }
- /**
- * array_column 一样用法
- */
- public static function arrayColumn($array, $column_key, $index_key = null): array
- {
- return $array && $array['records'] ? array_column($array['records'], $column_key, $index_key) : [];
- }
- /**
- * @param int $ipNum 每日ip次数限制
- * @param string $phone 手机号
- * @param int $phoneNum 每日单个手机号次数限制
- * @return array
- */
- public static function limitSmsSend(int $ipNum = 10, string $phone = '', int $phoneNum = 3):array
- {
- if ($ipNum > 0) {
- $ip = self::getUserHostIp();
- $key = 'limit_ip:' . date('Ymd') . '_' . $ip;
- if (RedisInstance::getInstance()->incr($key, 1, 86400) > $ipNum) {
- return Helper::commonError('今日短信次数超过限制i');
- }
- }
- if ($phone && $phoneNum > 0) {
- $key = 'limit_phone:' . date('Ymd') . '_' . $phone;
- if (RedisInstance::getInstance()->incr($key, 1, 86400) > $phoneNum) {
- return Helper::commonError('今日短信次数超过限制p');
- }
- }
- return Helper::commonReturn();
- }
- /**
- * 获取代理模式用户真实访问IP
- * 获取阿里云用户真实访问IP
- */
- public static function getUserHostIp()
- {
- if (isset($_SERVER['HTTP_X_ORIGINAL_FORWARDED_FOR']))
- {
- $ips = isset($_SERVER["HTTP_X_ORIGINAL_FORWARDED_FOR"]) ? explode(',', $_SERVER["HTTP_X_ORIGINAL_FORWARDED_FOR"]) : '';
- }
- else
- {
- $ips = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? explode(',', $_SERVER["HTTP_X_FORWARDED_FOR"]) : '';
- }
- if (isset($ips[0]))
- {
- $ip = $ips[0];
- }
- else
- {
- $ip = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : '';
- }
- return $ip ? $ip : '127.0.0.1';
- }
- public static function imageUpload($imagepath, $uploadpath)
- {
- try {
- $cosClient = new \Qcloud\Cos\Client(
- array(
- 'region' => 'ap-shanghai',
- // 'scheme' => 'https', //协议头部,默认为 http
- 'credentials'=> array(
- 'secretId' => 'AKIDviIeLyQluythLAykSJ6oXH91upgR6iT8' ,
- 'secretKey' => 'tobSCsOn7yc6ToBSWegaM9rVGyiR6f95'
- )
- )
- );
- $file = fopen($imagepath, "rb");
- if (!$file) {
- throw new Exception("读取图片失败");
- }
- $cosClient->putObject(['Bucket' => 'lewaimai-image-1251685925', 'Key' => $uploadpath, 'Body' => $file]);
- return Helper::commonReturn();
- } catch(Exception $e) {
- return Helper::commonError($e->getMessage());
- }
- }
- public static function imageDelete($path)
- {
- try {
- $cosClient = new \Qcloud\Cos\Client(
- array(
- 'region' => 'ap-shanghai',
- // 'scheme' => 'https', //协议头部,默认为 http
- 'credentials'=> array(
- 'secretId' => 'AKIDviIeLyQluythLAykSJ6oXH91upgR6iT8' ,
- 'secretKey' => 'tobSCsOn7yc6ToBSWegaM9rVGyiR6f95'
- )
- )
- );
- $cosClient->deleteObject(['Bucket' => 'lewaimai-image-1251685925', 'Key' => $path]);
- return Helper::commonReturn();
- } catch(Exception $e) {
- return Helper::commonError($e->getMessage());
- }
- }
- }
|