Loading... ```php /** * 生成匹配密码 * @url createPassword * @method GET * @param string $password 密码 * @param string $passsalt 盐 * @return string $str 生成的密码 */ function createPassword($password, $passsalt) { return md5(md5(md5($password)) . $passsalt); } /** * 获取用户真实IP地址 * @url getIp * @method GET * @return string $str IP地址 */ function getIp() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $cip = $_SERVER['HTTP_CLIENT_IP']; } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $cip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if (!empty($_SERVER["REMOTE_ADDR"])) { $cip = $_SERVER["REMOTE_ADDR"]; } else { $cip = ''; } preg_match("/[\d\.]{7,15}/", $cip, $cips); $cip = isset($cips[0]) ? $cips[0] : 'unknown'; unset($cips); return $cip; } /** * 二维数组根据某个字段排序 * @url arraySort * @method GET * @param array $array 要排序的数组 * @param string $keys 要排序的键字段 * @param string $sort 排序类型 SORT_ASC SORT_DESC * @return array $array 排序后的数组 */ function arraySort($array, $keys, $sort = SORT_DESC) { $keysValue = []; foreach ($array as $k => $v) { $keysValue[$k] = $v[$keys]; } array_multisort($keysValue, $sort, $array); return $array; } /** * base16加密 * @url base16_encode * @method GET * @param string $data 待加密字符串 * @return string $str 加密结果 */ function base16_encode($data) { $result = ""; $BASE_16_CHARS = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"); for ($i = 0; $i < strlen($data); $i++) { $result .= $BASE_16_CHARS[(@ord($data[$i]) & 0xf0) >> 4]; $result .= $BASE_16_CHARS[@ord($data[$i]) & 0x0f]; } return $result; } /** * base16解密 * @url base16_decode * @method GET * @param string $data 待解密字符串 * @return string $str 解密结果 */ function base16_decode($data) { $result = ""; $len = strlen($data) / 2; for ($i = 0; $i < $len; $i++) { $result .= chr(intval(substr($data, $i * 2, 2), 16)); } return $result; } /** * 图片base64编码 * @url imgBase64Encode * @method GET * @param string $img 待编码图片url地址 * @param bool $imgHtmlCode 是否加前缀 * @return string $str 结果 */ function imgBase64Encode($img = '', $imgHtmlCode = true) { //如果是本地文件 if (strpos($img, 'http') === false && !file_exists($img)) { return $img; } //获取文件内容 $file_content = file_get_contents($img); if ($file_content === false) { return $img; } $imageInfo = getimagesize($img); $prefiex = ''; if ($imgHtmlCode) { $prefiex = 'data:' . $imageInfo['mime'] . ';base64,'; } $base64 = $prefiex . chunk_split(base64_encode($file_content)); return $base64; } /** * GET 请求 * @url http_get * @method GET * @param string $url 请求地址 * @return array $array 结果 */ function http_get($url) { $oCurl = curl_init(); if (stripos($url, "https://") !== FALSE) { curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($oCurl, CURLOPT_VERBOSE, 1); curl_setopt($oCurl, CURLOPT_HEADER, 1); // $sContent = curl_exec($oCurl); // $aStatus = curl_getinfo($oCurl); $sContent = execCURL($oCurl); curl_close($oCurl); return $sContent; } /** * POST 请求 * @url http_post * @method GET * @param string $url 请求地址 * @param array $param 传递参数 * @param bool $post_file 是否文件上传 * @return array $array 结果 */ function http_post($url, $param, $post_file = false) { $oCurl = curl_init(); if (stripos($url, "https://") !== FALSE) { curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) { $is_curlFile = true; } else { $is_curlFile = false; if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false); } } if ($post_file) { if ($is_curlFile) { foreach ($param as $key => $val) { if (isset($val["tmp_name"])) { $param[$key] = new \CURLFile(realpath($val["tmp_name"]), $val["type"], $val["name"]); } else if (substr($val, 0, 1) == '@') { $param[$key] = new \CURLFile(realpath(substr($val, 1))); } } } $strPOST = $param; } else { $strPOST = json_encode($param); } curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($oCurl, CURLOPT_POST, true); curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST); curl_setopt($oCurl, CURLOPT_VERBOSE, 1); curl_setopt($oCurl, CURLOPT_HEADER, 1); // $sContent = curl_exec($oCurl); // $aStatus = curl_getinfo($oCurl); $sContent = execCURL($oCurl); curl_close($oCurl); return $sContent; } /** * 执行CURL请求,并封装返回对象 * @param $ch * @return array */ function execCURL($ch) { $response = curl_exec($ch); $error = curl_error($ch); $result = array('header' => '', 'content' => '', 'curl_error' => '', 'http_code' => '', 'last_url' => ''); if ($error != "") { $result['curl_error'] = $error; return $result; } $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $result['header'] = str_replace(array("\r\n", "\r", "\n"), "<br/>", substr($response, 0, $header_size)); $result['content'] = substr($response, $header_size); $result['http_code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE); $result['last_url'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); $result["base_resp"] = array(); $result["base_resp"]["ret"] = $result['http_code'] == 200 ? 0 : $result['http_code']; $result["base_resp"]["err_msg"] = $result['http_code'] == 200 ? "ok" : $result["curl_error"]; return $result; } /** * 给URL地址追加参数 * @url appendParamter * @method GET * @param string $url url地址 * @param string $key 键 * @param string $value 值 * @return string url 新的url地址 */ function appendParamter($url, $key, $value) { return strrpos($url, "?", 0) > -1 ? "$url&$key=$value" : "$url?$key=$value"; } /** * 生成指定长度的字符串 * @url createNonceStr * @method GET * @param int $length 生成字符串长度 * @return string $str 结果 */ function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } /** * 读取本地文件 * @url get_php_file * @method GET * @param string $filename 文件地址 * @return string $str 结果 */ function get_php_file($filename) { if (file_exists($filename)) { return trim(substr(file_get_contents($filename), 15)); } else { return '{"expire_time":0}'; } } /** * 写入本地文件 * @url set_php_file * @method GET * @param string $filename 文件地址 * @param string $content 内容 */ function set_php_file($filename, $content) { $fp = fopen($filename, "w"); fwrite($fp, "<?php exit();?>" . $content); fclose($fp); } /** * 判断是否为微信浏览器 * @url isWeixinBrowser * @method GET * @return bool $result 结果 */ function isWeixinBrowser() { if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) { return true; } else { return false; } } /** * 时间戳转日期 * @url timeToDate * @method GET * @param int $time 时间戳 * @param int $type 类型 * @return false|string $result 结果 */ function timeToDate($time = 0, $type = 6) { if (!$time) { $time = time(); } $typeArray = array('Y-m-d', 'Y', 'm-d', 'Y-m-d', 'm-d H:i', 'Y-m-d H:i', 'Y-m-d H:i:s'); return date($typeArray[$type], $time); } /** * 根据经纬度在腾讯地图获取详细地址信息 * @url getPositionInfo * @method GET * @param string $latitude * @param string $longitude * @return mixed string $str 结果 */ function getPositionInfo($latitude, $longitude) { global $ak; $data = changePositionToTengXun($latitude, $longitude); $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $data['latitudeNew'] . "," . $data['longitudeNew'] . "&key=$ak&get_poi=1"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } /** * 地址转坐标 * @url addressToPosition * @method GET * @param string $address 待转换地址 * @return mixed $str 结果 */ function addressToPosition($address) { global $ak; $url = "https://apis.map.qq.com/ws/geocoder/v1/?address=$address®ion=温州&key=$ak"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } /** * gps经纬度转为腾讯地图经纬度 * @url changePositionToTengXun * @method GET * @param string $latitude 纬度 * @param string $longitude 经度 * @return array $array 结果 */ function changePositionToTengXun($latitude, $longitude) { global $ak; $url = "https://apis.map.qq.com/ws/coord/v1/translate?locations=$latitude,$longitude&type=1&key=$ak"; $resultQ = json_decode(file_get_contents($url), true); $latitudeNew = $resultQ["locations"][0]["lat"]; $longitudeNew = $resultQ["locations"][0]["lng"]; $returnDataArray = array("latitudeNew" => $latitudeNew, "longitudeNew" => $longitudeNew); return $returnDataArray; } /** * 日期转时间戳 * @url changePositionToTengXun * @method GET * @param string $date 日期 * @return false|int|string $str 结果 */ function dateToTime($date) { $time = strtotime($date); if ($time === false) { if (class_exists('DateTime')) { $D = new DateTime($date); $time = $D->format('U'); } } return $time; } /** * 正数查找字符串n次出现的位置 * @url str_n_pos * @method GET * @param string $str 被查找的字符串 * @param string $find 查找的字符串 * @param int $n 第几次出现 * @return bool|int $result 结果 */ function str_n_pos($str, $find, $n = 1) { $pos_val = 0; for ($i = 1; $i <= $n; $i++) { $pos = strpos($str, $find); $str = substr($str, $pos + 1); $pos_val = $pos + $pos_val + 1; } return $pos_val - 1; } /** * 逆数查找字符串n次出现的位置 * @url str_n_rpos * @method GET * @param string $str 被查找的字符串 * @param string $find 查找的字符串 * @param int $n 第几次出现 * @return bool|int $result 结果 */ function str_n_rpos($str, $find, $n = 1) { $pos_val = 0; for ($i = 1; $i <= $n; $i++) { $pos = strrpos($str, $find); $str = substr($str, 0, $pos); $pos_val = $pos; } return $pos_val; } /** * 判断是否为有效的链接 * @url checkUrl * @method GET * @param string $C_url url地址 * @return bool $result 结果 */ function checkUrl($C_url) { $str = "/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/"; if (!preg_match($str, $C_url)) { return false; } else { return true; } } /** * 将数组拼接为sql语句 * @url insertSql * @method GET * @param string $table 表名称 * @param array $array 数组 * @return string $str 结果 */ function insertSql($table, $array) { $sqlk = ''; $sqlv = ''; foreach ($array as $k => $v) { $sqlk .= ',' . $k; $sqlv .= ",'$v'"; } $sqlk = substr($sqlk, 1); $sqlv = substr($sqlv, 1); $sql = "insert into $table ($sqlk) values ($sqlv)"; return $sql; } /** * 对富文本信息中的数据匹配出所有的 img 标签的 src属性 * @url getPatternMatchImages * @method GET * @param string $contentStr 富文本字符串 * @return array $result 结果 */ function getPatternMatchImages($contentStr = "") { $imgSrcArr = array(); //首先将富文本字符串中的 img 标签进行匹配 $pattern_imgTag = '/<img\b.*?(?:\>|\/>)/i'; preg_match_all($pattern_imgTag, $contentStr, $matchIMG); if (isset($matchIMG[0])) { foreach ($matchIMG[0] as $key => $imgTag) { //进一步提取 img标签中的 src属性信息 $pattern_src = '/\bsrc\b\s*=\s*[\'\"]?([^\'\"]*)[\'\"]?/i'; preg_match_all($pattern_src, $imgTag, $matchSrc); if (isset($matchSrc[1])) { foreach ($matchSrc[1] as $src) { //将匹配到的src信息压入数组 $imgSrcArr[] = $src; } } } } return $imgSrcArr; } /** * 记录日志内容 * @url write_log * @method GET * @param string $msg 内容 * @param string $filename 日志文件路径 * @return null */ function write_log($msg, $filename="./msg.log") { $file = fopen($filename, "a"); $msg = "[" . date("Y-m-d H:i:s") . "] - " . $msg; fwrite($file, $msg . "\n"); fclose($file); } /** * 判断访问设备 * @url isMobile * @method GET * @return bool $result 结果 */ function isMobile() { // 如果有HTTP_X_WAP_PROFILE则一定是移动设备 if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) { return true; } // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息 if (isset ($_SERVER['HTTP_VIA'])) { // 找不到为false,否则为true return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false; } // 脑残法,判断手机发送的客户端标志,兼容性有待提高 if (isset ($_SERVER['HTTP_USER_AGENT'])) { $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile' ); // 从HTTP_USER_AGENT中查找手机浏览器的关键字 if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) { return true; } } // 协议法,因为有可能不准确,放到最后判断 if (isset ($_SERVER['HTTP_ACCEPT'])) { // 如果只支持wml并且不支持html那一定是移动设备 // 如果支持wml和html但是wml在html之前则是移动设备 if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) { return true; } } return false; } /** * 封装返回json数据 * @url json * @method GET * @param int $statusCode 状态码 * @param string $message 消息 * @param array $data 数据 * @return string $str 结果 */ function json($statusCode, $message = '', $data = array()) { if (!$message) { $httpStatus = array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '(Unused)', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported' ); $message = $httpStatus[$statusCode]; } $response = array( "code" => $statusCode, "msg" => $message ); $response["data"] = $data; return json_encode($response); } ``` 最后修改:2023 年 08 月 20 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏