常用助手函数

[TOC]

CURL 后端访问接口

* $method参数可以指定请求方式 get 或post * $url参数可以指定要请求的地址 * $param为设置的get或者post的参数 * $timeout设置为1为异步请求,设置数值稍大则可以视为同步请求
function curl_common($method='get', $url = '', $param = [], $header = [], $timeout =1) { $curl = curl_init(); //初始化curl curl_setopt($curl, CURLOPT_URL, $url); //抓取指定网页 curl_setopt($curl, CURLOPT_HEADER, 0); //设置header curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上 curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //设置头部 curl_setopt($curl, CURLOPT_HEADER, 0); //返回头部信息 if('get' ==$method){ $url .= '?'.http_build_query($param); }else{ curl_setopt($curl, CURLOPT_POST, 1); //post提交方式 curl_setopt($curl, CURLOPT_POSTFIELDS, $param); //post提交数据 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl协议 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); } curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); //设置超时时间 $data = curl_exec($curl); //运行curl curl_close($curl); return $data; }

人性化显示某时间距离当前已经过去多久

//$sTime int 时间戳 function formatTime($sTime, $formt = 'Y-m-d') { if (!$sTime) { return ''; } //sTime=源时间,cTime=当前时间,dTime=时间差 $cTime = $_SERVER['REQUEST_TIME']; $dTime = $cTime - $sTime; $dDay = intval(date('z', $cTime)) - intval(date('z', $sTime)); $dYear = intval(date('Y', $cTime)) - intval(date('Y', $sTime)); //n秒前,n分钟前,n小时前,日期 if ($dTime < 60) { if ($dTime < 10) { return '刚刚'; } else { return intval(floor($dTime / 10) * 10).'秒前'; } } elseif ($dTime < 3600) { return intval($dTime / 60).'分钟前'; } elseif ($dYear == 0 && $dTime >= 3600 && $dDay == 0) { return intval($dTime / 3600).'小时前'; } elseif ($dYear == 0 && $dDay > 0 && $dDay <= 7) { return intval($dDay).'天前'; } elseif ($dYear == 0 && $dDay > 7 && $dDay <= 30) { return intval($dDay / 7).'周前'; } elseif ($dYear == 0 && $dDay > 30) { return intval($dDay / 30).'个月前'; } elseif ($dYear == 0) { return date('m月d日', $sTime); } else { return date($formt, $sTime); } }

获取客户端设备类型(Windows、Mac、ihpone、Android、Linux等)

function getClientOsInfo() { @$agent = $_SERVER['HTTP_USER_AGENT']; $os = false; if (preg_match('/win/i', $agent) && strpos($agent, '95')) { $os = 'Windows 95'; } elseif (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) { $os = 'Windows ME'; } elseif (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) { $os = 'Windows 98'; } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) { $os = 'Windows Vista'; } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) { $os = 'Windows 7'; } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) { $os = 'Windows 8'; } elseif (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) { $os = 'Windows 10'; } elseif (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) { $os = 'Windows XP'; } elseif (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) { $os = 'Windows 2000'; } elseif (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) { $os = 'Windows NT'; } elseif (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) { $os = 'Windows 32'; } elseif (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) { $os = 'SunOS'; } elseif (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) { $os = 'IBM OS/2'; } elseif (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) { $os = 'Mac'; } elseif (preg_match('/PowerPC/i', $agent)) { $os = 'PowerPC'; } elseif (preg_match('/AIX/i', $agent)) { $os = 'AIX'; } elseif (preg_match('/HPUX/i', $agent)) { $os = 'HPUX'; } elseif (preg_match('/NetBSD/i', $agent)) { $os = 'NetBSD'; } elseif (preg_match('/BSD/i', $agent)) { $os = 'BSD'; } elseif (preg_match('/OSF1/i', $agent)) { $os = 'OSF1'; } elseif (preg_match('/IRIX/i', $agent)) { $os = 'IRIX'; } elseif (preg_match('/FreeBSD/i', $agent)) { $os = 'FreeBSD'; } elseif (preg_match('/teleport/i', $agent)) { $os = 'teleport'; } elseif (preg_match('/flashget/i', $agent)) { $os = 'flashget'; } elseif (preg_match('/webzip/i', $agent)) { $os = 'webzip'; } elseif (preg_match('/offline/i', $agent)) { $os = 'offline'; } elseif (preg_match('/ipod/i', $agent)) { $os = 'ipod'; } elseif (preg_match('/ipad/i', $agent)) { $os = 'ipad'; } elseif (preg_match('/iphone/i', $agent)) { $os = 'iphone'; } elseif (preg_match('/android/i', $agent)) { $os = 'Android'; } elseif (preg_match('/linux/i', $agent)) { $os = 'Linux'; } elseif (preg_match('/unix/i', $agent)) { $os = 'Unix'; } else { $os = '未知操作系统'; } return $os; }

文件批量重命名程序

function resetname() { $dir1 = './aaa/';//读取文件夹名称 $dir2 = './aaa1/';//移动到文件夹名称 $filearr = scandir($dir1);//读取文件夹 unset($filearr[0]);//去除多余的元素 unset($filearr[1]); $filearr = array_values($filearr);//使数组从0开始,以1递增 $filecount = count($filearr);//文件数量 $onenum = 1;//起始编号 $maxnum = $onenum + $filecount;//最大循环次数 $title = '';//'隋唐演义';//文件标题 $houzhui = '.jpg';//文件后缀 for ($i = $onenum; $i <= $maxnum; $i++) { for ($j=0; $j < $filecount ; $j++) { $filename = $title.$i.$houzhui; rename($dir1.$filearr[$j],$dir2.iconv("utf-8","gb2312",$filename));//设置字符集 $i++; } } return 'ok'; }

统一构造的失败或成功的JSON响应

function success($data, $msg = null) { return json_encode( [ 'status' => 1, 'msg' => $msg ?? '请求成功', 'data' => $data, ] ); } function fail($msg = '请求失败') { return json_encode( [ 'status' => 0, 'msg' => $msg, ] ); }

自定义数组过滤

  • 可以自定义一个回调方法,返回 true或false 来决定是否过滤
array_filter($data,'filtrArr'); function filtrArr($arr) { if($arr === '' || $arr === null){ return false; } return true; }

文件上传到本地

use Illuminate\Support\Facades\Storage; function upload($request) { $images = $request->file(); $image = ''; foreach ($images as $key => $value) { $image = $value; } $channel = 'public'; $path = Storage::putFile($channel, $image); if ($path) { $url = env('APP_URL').Storage::url($path); return $url; //文件路径 } else { return fail('上传失败'); } }

资产的操作(金币/积分等平台币的处理)

  • 对于资产的操作一般比较敏感,所以最好有一个健全的易维护的统一的处理机制
  • 还需要考虑交易过程中的安全问题,所以交易是一个很复杂的过程,必须封装,以免不小心出现错误
function sumPoint($uid, $num, $note) { $exists = DB::table('users')->where('id', $uid)->exists(); if (!$exists || $num<0) { return false; } try { DB::transaction(function () use ($uid, $num, $note) { $latest = bcsub($origin,$num,2); $origin = DB::table('users')->where('id', $uid)->value('point'); DB::table('users')->where('id', $uid)->update([ 'point'=> bcadd($origin, $num, 2)]); DB::table('financial_logs')->insert([ 'user_id' => $uid, 'type' => 1,//1=收入 2=支出 'num' => $num, 'latest' => bcadd($origin, $num, 2), 'note' => $note, ]); }, 5); return true; }catch(Exception $e) { return false; } return true; }
function subPoint($uid, $num, $note) { $exists = DB::table('users')->where('id', $uid)->exists(); if (!$exists || $num>0) { return false; } $asset = 'point'; $origin = DB::table('users')->where('id', $uid)->value($asset); if ($origin < $num) { return false; } try { DB::transaction(function () use ($uid, $num, $note) { $latest = bcsub($origin,$num,2); $origin = DB::table('users')->where('id', $uid)->value('point'); DB::table('users')->where('id', $uid)->update([ 'point'=> $latest]); DB::table('financial_logs')->insert([ 'user_id' => $uid, 'type' => 2,//1=收入 2=支出 'num' => $num, 'latest' => $latest, 'note' => $note, ]); }, 5); return true; }catch(Exception $e) { return false; } return true; }

获取用户的IP地址

function get_ip() { if (isset($_SERVER)) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $realip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $realip = $_SERVER['HTTP_CLIENT_IP']; } else { $realip = $_SERVER['REMOTE_ADDR']; } } else { if (getenv('HTTP_X_FORWARDED_FOR')) { $realip = getenv('HTTP_X_FORWARDED_FOR'); } elseif (getenv('HTTP_CLIENT_IP')) { $realip = getenv('HTTP_CLIENT_IP'); } else { $realip = getenv('REMOTE_ADDR'); } } return $realip; }

计算两点地理坐标之间的距离.

/** * 计算两点地理坐标之间的距离. * * @param Decimal $longitude1 起点经度 * @param Decimal $latitude1 起点纬度 * @param Decimal $longitude2 终点经度 * @param Decimal $latitude2 终点纬度 * @param int $unit 单位 1:米 2:公里 * @param int $decimal 精度 保留小数位数 * * @return Decimal */ function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit = 1, $decimal = 2) { $EARTH_RADIUS = 6370.996; // 地球半径系数 $PI = 3.1415926; $radLat1 = $latitude1 * $PI / 180.0; $radLat2 = $latitude2 * $PI / 180.0; $radLng1 = $longitude1 * $PI / 180.0; $radLng2 = $longitude2 * $PI / 180.0; $a = $radLat1 - $radLat2; $b = $radLng1 - $radLng2; $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))); $distance = $distance * $EARTH_RADIUS * 1000; if ($unit == 2) { $distance = $distance / 1000; } return round($distance, $decimal); }

基于GEOHASH附近的人功能实现

  • GEOHASH 可以将一个地址映射成为一个字符串,通过比较字符串的相似度,确定两个坐标的大概距离
  • //1=5000km;2=1000km;3=100km 4=40km 5=5km 6=1km 7=100m 8=50m 9=5m 10=1m 11=10cm 12=5cm
  • 已知自身坐标位置,可以去找附近范围的人,也可以比较自己与附近人的范围
function getgeohash($longitude, $latitude) { return GeoHash::encode($longitude, $latitude); } function compareGeohash($geohash1, $geohash2) { $map = [ '0' => '>5000km 距离过远', '1' => '<5000km 距离过远', '2' => '<1000km 距离过远', '3' => '<100km 不建议步行', '4' => '<40km 不建议步行', '5' => '<5km 20分钟', '6' => '<1km 10分钟', '7' => '<500m 5分钟', '8' => '<50m 1分钟', '9' => '<5m 1分钟', '10' => '<1m 1分钟', ]; $len = 10; for ($i=$len;$i>0;$i--) { $key1 = substr($geohash1, 0, $i); $key2 = substr($geohash2, 0, $i); if ($key1 == $key2) { return $map[$i]; } } return '系统故障,无法测算'; } 
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 2年前 自动加精
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!