文件处理
function p($data, $force = false, $file = null)
{
is_null($file) && $file = env('runtime_path') . date('Ymd') . '.txt';
$str = ((is_string($data) ? $data : (is_array($data) || is_object($data))) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
$force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
}
function wx_log($domainname, $filename)
{
$years = date('Y-m-d');
$url = $filename . date('Ymd') . 'log.txt';
$dir_name = dirname($url);
if (!file_exists($dir_name)) {
$res = mkdir(iconv("UTF-8", "GBK", $dir_name), 0777, true);
}
$fp = fopen($url, "a");
fwrite($fp, date("Y-m-d H:i:s") . var_export($domainname, true) . "\r\n");
}
function base64EncodeImage ($image_file) {
$base64_image = '';
$image_info = getimagesize($image_file);
$image_data = fread(fopen($image_file, 'r'), filesize($image_file));
$base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
return urlencode($base64_image);
}
function getUriLen($uri,$user='',$pw='')
{
ob_start();
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
if (!empty($user) && !empty($pw))
{
$headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$okay = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s+(.+)/';
preg_match($regex, $head, $matches);
return $matches[1];
}
function getCode($num,$w,$h,$code_name) {
$code = "";
for ($i = 0;$i < $num; $i++){
$code .= rand(0, 9);
}
Cache::set($code_name,$code,600);
header("Content-type: image/PNG");
$im = imagecreate($w, $h);
$black = imagecolorallocate($im, 0, 0, 0);
$gray = imagecolorallocate($im, 200, 200, 200);
$bgcolor = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $gray);
imagerectangle($im, 0, 0, $w-1, $h-1, $black);
$style = array ($black,$black,$black,$black,$black, $gray,$gray,$gray,$gray,$gray);
imagesetstyle($im, $style);
$y1 = rand(0, $h);
$y2 = rand(0, $h);
$y3 = rand(0, $h);
$y4 = rand(0, $h);
imageline($im, 0, $y1, $w, $y3, IMG_COLOR_STYLED);
imageline($im, 0, $y2, $w, $y4, IMG_COLOR_STYLED);
for ($i = 0; $i < 80; $i++) {
imagesetpixel($im, rand(0, $w), rand(0, $h), $black);
}
$strx = rand(3, 8);
for ($i = 0; $i < $num; $i++) {
$strpos = rand(1, 6);
imagestring($im, 5, $strx, $strpos, substr($code, $i, 1), $black);
$strx += rand(8, 12);
}
imagepng($im);
imagedestroy($im);
}
function file_format($str){
$str=strtolower(pathinfo($str, PATHINFO_EXTENSION));
$image=array('webp','jpg','png','ico','bmp','gif','tif','pcx','tga','bmp','pxc','tiff','jpeg','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','hdri');
$video=array('mp4','avi','3gp','rmvb','gif','wmv','mkv','mpg','vob','mov','flv','swf','mp3','ape','wma','aac','mmf','amr','m4a','m4r','ogg','wav','wavpack');
$zip=array('rar','zip','tar','cab','uue','jar','iso','z','7-zip','ace','lzh','arj','gzip','bz2','tz');
$text=array('exe','doc','ppt','xls','wps','txt','lrc','wfs','torrent','html','htm','java','js','css','less','php','pdf','pps','host','box','docx','word','perfect','dot','dsf','efe','ini','json','lnk','log','msi','ost','pcs','tmp','xlsb');
switch ($str) {
case in_array($str, $image):
return 'image';
break;
case in_array($str, $video):
return 'video';
break;
case in_array($str, $zip):
return 'zip';
break;
case in_array($str, $text):
return 'text';
break;
default:
return 'image';
break;
}
}
function base64_image($content, $dirname = 'base64/')
{
try {
if (preg_match('|^data:image/(.*?);base64,|i', $content)) {
list($ext, $base) = explode('|||', preg_replace('|^data:image/(.*?);base64,|i', '$1|||', $content));
$info = File::save($dirname . md5($base) . '.' . (empty($ext) ? 'tmp' : $ext), base64_decode($base));
return $info['url'];
} else {
return $content;
}
} catch (\Exception $e) {
return $content;
}
}
function do_rmdir($dirname, $self = true) {
if (!file_exists($dirname)) {
return false;
}
if (is_file($dirname) || is_link($dirname)) {
return unlink($dirname);
}
$dir = dir($dirname);
if ($dir) {
while (false !== $entry = $dir->read()) {
if ($entry == '.' || $entry == '..') {
continue;
}
do_rmdir($dirname . '/' . $entry);
}
}
$dir->close();
$self && rmdir($dirname);
}
function allFile($path = __DIR__, $level = 1)
{
if (is_dir($path) && is_readable($path)) {
if($pd = opendir($path)) {
while (($file = readdir($pd)) !== false) {
if($file != '.' && $file != '..') {
if (($subPath = $path . DIRECTORY_SEPARATOR . $file) && is_dir($subPath)) {
echo "<pre />";
echo '<span style="color: red;font-weight:bold;">' . str_repeat("--", $level) . $subPath . '</span>';
self::allFile($subPath, $level++);
} else {
echo "<pre />";
echo str_repeat("--", $level) . $subPath;
}
}
}
}
} else {
echo "{$path} is not a available dir";
}
}
手机号处理
function createNoncePone($header='100',$length = 8) {
$chars = "0123456789";
$str = $header;
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
function checkPhone($phone){
return preg_match('/(^1\d{10})$/',$phone);
}
function encryptTel($tel){
return substr_replace($tel, '****', 3, 4);
}
function checkMobile($sMobile)
{
$sPregMatch = '/^1(3[0-9]|4[57]|5[0-35-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/';
return preg_match($sPregMatch, $sMobile);
}
时间处理
function format_datetime($datetime, $format = 'Y年m月d日 H:i:s')
{
return date($format, strtotime($datetime));
}
function getNow()
{
ini_set('date.timezone', 'Asia/Shanghai');
return date("Y-m-d H:i:s");
}
function getNowMicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return date('Y-m-d H:i:s', $sec) . '.' . substr($usec, 2, 6);
}
function diffBetweenTwoDays($day1, $day2)
{
$second1 = strtotime($day1);
$second2 = strtotime($day2);
if ($second1 < $second2) {
$tmp = $second2;
$second2 = $second1;
$second1 = $tmp;
}
return ($second1 - $second2) / 86400;
}
function cut_up_time_part($start, $end, $nums = 7, $format = true)
{
$start = strtotime($start);
$end = strtotime($end);
$parts = ($end - $start) / $nums;
$last = ($end - $start) % $nums;
if ($last > 0) {
$parts = ($end - $start - $last) / $nums;
}
for ($i = 1; $i <= $nums; $i++) {
$_end = $start + $parts * $i;
$arr[] = array($start + $parts * ($i - 1), $_end);
}
$len = count($arr) - 1;
$arr[$len][1] = $arr[$len][1] + $last;
if ($format) {
foreach ($arr as $key => $value) {
$arr[$key][0] = date("Y-m-d", $value[0]);
$arr[$key][1] = date("Y-m-d", $value[1]);
}
}
return $arr;
}
function getNowMicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return date('Y-m-d H:i:s',$sec).'.'.substr($usec,2,6);
}
function microtime_float()
{
return microtime(true)*10000;
}
function formatRestTime($date, $hour = 6){
if (strtotime($date) == time() && $hour == 24) {
return '23:59:59';
}
if (strtotime($date) < strtotime('-' . $hour . ' hour')) {
return 0;
}
$times = 3600 * $hour - (time() - strtotime($date));
$day = 0;
$hour = floor(($times-86400 * $day)/3600);
$second = $times%3600;
$minute = floor($second/60);
$second = $second%60;
return $hour.':'.$minute.':'.$second;
}
function timediff( $begin_time, $end_time )
{
if ( $begin_time < $end_time ) {
$starttime = $begin_time;
$endtime = $end_time;
}
$timediff = $endtime - $starttime;
$days = intval( $timediff / 86400 );
$remain = $timediff % 86400;
$hours = intval( $remain / 3600 );
$remain = $remain % 3600;
$mins = intval( $remain / 60 );
$secs = $remain % 60;
return $hours.':'.$mins.':'.$secs;
}
function date_range($first, $last, $step = '+1 day', $output_format = 'd/m/Y' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
function excelTime($date, $time = false) {
if(function_exists('GregorianToJD')){
if (is_numeric( $date )) {
$jd = GregorianToJD( 1, 1, 1970 );
$gregorian = JDToGregorian( $jd + intval ( $date ) - 25569 );
$date = explode( '/', $gregorian );
$date_str = str_pad( $date [2], 4, '0', STR_PAD_LEFT )
."-". str_pad( $date [0], 2, '0', STR_PAD_LEFT )
."-". str_pad( $date [1], 2, '0', STR_PAD_LEFT )
. ($time ? " 00:00:00" : '');
return $date_str;
}
}else{
$date=$date>25568?$date+1:25569;
$ofs=(70 * 365 + 17+2) * 86400;
$date = date("Y-m-d",($date * 86400) - $ofs).($time ? " 00:00:00" : '');
}
return $date;
}
function time_ago($agoTime)
{
$agoTime = (int)$agoTime;
$time = time() - $agoTime;
if ($time >= 31104000) {
$num = (int)($time / 31104000);
return $num.'年前';
}
if ($time >= 2592000) {
$num = (int)($time / 2592000);
return $num.'月前';
}
if ($time >= 86400) {
$num = (int)($time / 86400);
return $num.'天前';
}
if ($time >= 3600) {
$num = (int)($time / 3600);
return $num.'小时前';
}
if ($time > 60) {
$num = (int)($time / 60);
return $num.'分钟前';
}
return '1分钟前';
}
function get_week(){
$wk_day=date('w');
$day=date('d');
$week=array('日','一','二','三','四','五','六');
$d=ceil($day/7);
$str=date("Y年n月j日")." 星期".$week[$wk_day]." - 本月的第 ".$d." 个星期".$week[$wk_day];
return $str;
}
字符串处理
function addviews($num=0,$max=5){
return $num+rand(0,$max);
}
function _encrypt($data, $key, $expire = 0) {
$key = md5($key);
$data = base64_encode($data);
$x = 0;
$len = strlen($data);
$l = strlen($key);
$char = '';
for ($i = 0; $i < $len; $i++) {
if ($x == $l) $x=0;
$char .= substr($key, $x, 1);
$x++;
}
$str = sprintf('%010d', $expire ? $expire + time() : 0);
for ($i = 0; $i < $len; $i++) {
$str .= chr(ord(substr($data,$i,1)) + (ord(substr($char,$i,1)))%256);
}
$str = base64_encode($str);
echo $str.'<br>';
$str = str_replace(array('=','+','/'),array('O0O0O','o000o','oo00o'),$str);
$str .= '-'.md5($str);
return $str;
}
function _decrypt($data, $key){
$dataary = explode('-',$data);
if (md5($dataary[0]) != $dataary[1]){
return '数据错误';
}
$data = str_replace(array('O0O0O','o000o','oo00o'), array('=','+','/'),$dataary[0]);
$key = md5($key);
$x = 0;
$data = base64_decode($data);
$expire = substr($data, 0, 10);
$data = substr($data, 10);
if($expire > 0 && $expire < time()) {
return '已过期';
}
$len = strlen($data);
$l = strlen($key);
$char = $str = '';
for ($i = 0; $i < $len; $i++) {
if ($x == $l) $x = 0;
$char .= substr($key, $x, 1);
$x++;
}
for ($i = 0; $i < $len; $i++) {
if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
}
else{
$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
}
}
return base64_decode($str);
}
function encode($string)
{
list($chars, $length) = ['', strlen($string = iconv('utf-8', 'gbk', $string))];
for ($i = 0; $i < $length; $i++) {
$chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
}
return $chars;
}
function decode($string)
{
$chars = '';
foreach (str_split($string, 2) as $char) {
$chars .= chr(intval(base_convert($char, 36, 10)));
}
return iconv('gbk', 'utf-8', $chars);
}
function createNonceStr($length = 10, $letter = '')
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return date('Ymd', time()) . $letter . $str;
}
function Emojiencode($content)
{
return json_decode(preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($maps) {
return addslashes($maps[0]);
}, json_encode($content))
);
}
function Strunique($str)
{
$arr = explode(',', $str);
$arr = array_unique($arr);
$data = '';
foreach ($arr as $key => $value) {
$data .= $value . ',';
}
$data = trim($data, ',');
return $data;
}
function ucwordsString($str)
{
$str = str_replace('_', ' ', $str);
$str = ucwords($str);
$str = str_replace(' ', '', $str);
$str = lcfirst($str);
echo $str;
}
function log_contents_reg($type, $str)
{
$result = array();
if (is_array($str)) {
return false;
}
if ($type == '<') {
preg_match_all("/^(.*)(?:<)/i", $str, $result);
}
if ($type == '<>') {
preg_match_all("/(?:<)(.*)(?:>)/i", $str, $result);
}
if ($type == '()') {
preg_match_all("/(?:\()(.*)(?:\))/i", $str, $result);
}
if ($type == '[]') {
preg_match_all("/(?:\[)(.*)(?:\])/i", $str, $result);
}
if ($type == '{}') {
preg_match_all("/(?:\{)(.*)(?:\})/i", $str, $result);
}
return $result[1][0];
}
function cutLongStr($str, $len = 10){
if (!$str) {
return '';
}
if (mb_strlen($str) < 10) {
return $str;
}
return mb_substr($str, 0, 10) . '...';
}
function encrypString($str='',$starStart=1,$starNum=3){
$strlen = mb_strlen($str);
$ret = mb_substr($str,0,$starStart);
if($strlen>$starStart){
if($strlen<($starStart+$starNum)){
$starNum = $strlen-$starStart;
}
for($i=0;$i<$starNum;$i++){
$ret .= '*';
}
if($strlen>($starStart+$starNum)){
$ret .= mb_substr($str,$starStart+$starNum,$strlen);
}
}
return $ret;
}
function filterEmoji($str)
{
$str = preg_replace_callback(
'/./u',
function (array $match) {
return strlen($match[0]) >= 4 ? '' : $match[0];
},
$str);
$regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
return preg_replace($regex,"",$str);
}
function myTrim($str)
{
$search = array(" "," ","\n","\r","\t");
$replace = array("","","","","");
return str_replace($search, $replace, $str);
}
function deletehtml($str) {
$str = trim($str);
$str = strip_tags($str);
$str = preg_replace("/\r\n/", "", $str);
$str = preg_replace("/\r/", "", $str);
$str = preg_replace("/\n/", "", $str);
$str = preg_replace("/ /", "", $str);
$str = preg_replace("/ /", "", $str);
$str = str_replace(" ", "", $str);
$str = str_replace("·", "", $str);
$str = str_replace("”", "", $str);
$str = str_replace("“", "", $str);
return trim($str);
}
function get_order_num(){
$order_date = date('Y-m-d');
$order_id_main = date('YmdHis') . rand(10000000,99999999);
$order_id_len = strlen($order_id_main);
$order_id_sum = 0;
for($i=0; $i<$order_id_len; $i++){
$order_id_sum += (int)(substr($order_id_main,$i,1));
}
$order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
return $order_id;
}
function subText($text, $length)
{
if (mb_strlen($text, 'utf8') > $length) {
return mb_substr($text, 0, $length, 'utf8') . '...';
} else {
return $text;
}
}
function md5pwd($pwd){
$pwd = md5(sha1($pwd).'..*123qwe');
return $pwd;
}
-
将内容进行UNICODE编码,编码后的内容格式:\u56fe\u7247 (原始:图片)
function unicode_encode($name)
{
$name = iconv('UTF-8', 'UCS-2', $name);
$len = strlen($name);
$str = '';
for ($i = 0; $i < $len - 1; $i = $i + 2)
{
$c = $name[$i];
$c2 = $name[$i + 1];
if (ord($c) > 0)
{
$str .= '\u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
}
else
{
$str .= $c2;
}
}
return $str;
}
function unicode_decode($name)
{
$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
preg_match_all($pattern, $name, $matches);
if (!empty($matches))
{
$name = '';
for ($j = 0; $j < count($matches[0]); $j++)
{
$str = $matches[0][$j];
if (strpos($str, '\\u') === 0)
{
$code = base_convert(substr($str, 2, 2), 16, 10);
$code2 = base_convert(substr($str, 4), 16, 10);
$c = chr($code).chr($code2);
$c = iconv('UCS-2', 'UTF-8', $c);
$name .= $c;
}
else
{
$name .= $str;
}
}
}
return $name;
}
function EnglishOrChinese($str){
$strA= trim($str);
$lenA= strlen($strA);
$lenB= mb_strlen($strA, "utf-8");
if($lenA=== $lenB) {
return 'ENGLISH';
}else {
if($lenA% $lenB== 0) {
return 'CHINESE';
}else {
return 'MIXTURE';
}
}
}
网络请求相关
function is_weixin()
{
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
return true;
}
return false;
}
function isMobile()
{
if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
{
return true;
}
if (isset ($_SERVER['HTTP_VIA']))
{
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'
);
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
{
return true;
}
}
if (isset ($_SERVER['HTTP_ACCEPT']))
{
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;
}
function web_jump($url=''){
if(empty($url))$url = '/';
echo " <body><script language = 'javascript' type = 'text/javascript' > ";
echo " window.location.href = '$url' ";
echo " </script ></body> ";
}
function getUrlParameter($url)
{
if (stripos($url, '?') !== false) {
$uri_array = explode('?', $url);
$p_array = explode('&', $uri_array[1]);
foreach ($p_array as $k => $v) {
if (!$v) {
unset($p_array[$k]);
}
}
$newArr = array();
foreach ($p_array as $v) {
$t = explode('=', $v);
$newArr[$t[0]] = $t[1];
}
return $newArr;
}
}
function UrlUnsetParam($paramArray,$url) {
if($paramArray){
foreach ($paramArray as $val){
$url = preg_replace(
array("/{$val}=[^&]*/i", '/[&]+/', '/\?[&]+/', '/[?&]+$/',),
array('', '&', '?','',),
$url
);
}
}
return $url;
}
function getRefererUrl(){
$referer = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
return $referer;
}
function getUserAgent(){
return $_SERVER["HTTP_USER_AGENT"];
}
function checkUrl($url){
return preg_match('/[a-z]+:\/\/[a-z0-9_\-\/.%]+/i',$url);
}
function https_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
function http_curl($url, $method='GET', $data='',$type=''){
$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_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
if($type=='JSON'){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8'));
}
if($method=='POST'){
curl_setopt($curl, CURLOPT_POST, 1);
if($type='file'){
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}else{
if ($data != ''){
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
}
}
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$tmpInfo = curl_exec($curl);
curl_close($curl);
return $tmpInfo;
}
function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
function getClientBrowser($agent = '') {
$browser = '';
$browser_ver = '';
if (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
$browser = 'OmniWeb';
$browser_ver = $regs[2];
}
if (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
$browser = 'Netscape';
$browser_ver = $regs[2];
}
if (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
$browser = 'Safari';
$browser_ver = $regs[1];
}
if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
$browser = 'Internet Explorer';
$browser_ver = $regs[1];
}
if (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
$browser = 'Opera';
$browser_ver = $regs[1];
}
if (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
$browser = '(Internet Explorer '.$browser_ver.') NetCaptor';
$browser_ver = $regs[1];
}
if (preg_match('/Maxthon/i', $agent, $regs)) {
$browser = '(Internet Explorer '.$browser_ver.') Maxthon';
$browser_ver = '';
}
if (preg_match('/360SE/i', $agent, $regs)) {
$browser = '(Internet Explorer '.$browser_ver.') 360SE';
$browser_ver = '';
}
if (preg_match('/SE 2.x/i', $agent, $regs)) {
$browser = '(Internet Explorer '.$browser_ver.') 搜狗';
$browser_ver = '';
}
if (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
$browser = 'FireFox';
$browser_ver = $regs[1];
}
if (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
$browser = 'Lynx';
$browser_ver = $regs[1];
}
if (preg_match('/Chrome\/([^\s]+)/i', $agent, $regs)) {
$browser = 'Chrome';
$browser_ver = $regs[1];
}
if (preg_match('/MicroMessenger\/([^\s]+)/i', $agent, $regs)) {
$browser = '微信浏览器';
$browser_ver = $regs[1];
}
if ($browser != '') {
return ['browser'=>$browser, 'browser_ver'=>$browser_ver];
} else {
return ['browser'=>'未知','browser_ver'=> ''];
}
}
function robots(){
$useragent = addslashes(strtolower($_SERVER['HTTP_USER_AGENT']));
if (strpos($useragent, 'googlebot')!== false){$bot = 'Google';}
elseif (strpos($useragent,'mediapartners-google') !== false){$bot = 'Google Adsense';}
elseif (strpos($useragent,'baiduspider') !== false){$bot = 'Baidu';}
elseif (strpos($useragent,'sogou spider') !== false){$bot = 'Sogou';}
elseif (strpos($useragent,'sogou web') !== false){$bot = 'Sogou web';}
elseif (strpos($useragent,'sosospider') !== false){$bot = 'SOSO';}
elseif (strpos($useragent,'360spider') !== false){$bot = '360Spider';}
elseif (strpos($useragent,'haosou') !== false){$bot = 'haosou';}
elseif (strpos($useragent,'yahoo') !== false){$bot = 'Yahoo';}
elseif (strpos($useragent,'msn') !== false){$bot = 'MSN';}
elseif (strpos($useragent,'msnbot') !== false){$bot = 'msnbot';}
elseif (strpos($useragent,'sohu') !== false){$bot = 'Sohu';}
elseif (strpos($useragent,'yodaoBot') !== false){$bot = 'Yodao';}
elseif (strpos($useragent,'twiceler') !== false){$bot = 'Twiceler';}
elseif (strpos($useragent,'ia_archiver') !== false){$bot = 'Alexa_';}
elseif (strpos($useragent,'iaarchiver') !== false){$bot = 'Alexa';}
elseif (strpos($useragent,'slurp') !== false){$bot = '雅虎';}
elseif (strpos($useragent,'bot') !== false){$bot = $useragent;}
if(isset($bot)){
return array('date'=>date('Y-m-d H:i:s'),'ip'=>$_SERVER["REMOTE_ADDR"],'spider'=>$bot,'url'=>$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]);
}
}
json处理
function json_encode_ex($value)
{
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$str = json_encode($value);
$str = preg_replace_callback(
"#\\\u([0-9a-f]{4})#i",
function ($matchs) {
return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
},
$str
);
return $str;
} else {
return json_encode($value, JSON_UNESCAPED_UNICODE);
}
}
function analyJson($json_str)
{
$json_str = str_replace('\\', '', $json_str);
$out_arr = array();
preg_match('/{.*}/', $json_str, $out_arr);
if (!empty($out_arr)) {
$result = json_decode($out_arr[0], TRUE);
} else {
return FALSE;
}
return $result;
}
function json_encode_ex($value)
{
if (version_compare(PHP_VERSION,'5.4.0','<'))
{
$str = json_encode($value);
$str = preg_replace_callback(
"#\\\u([0-9a-f]{4})#i",
function( $matchs)
{
return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
},
$str
);
return $str;
}
else
{
return json_encode( $value, JSON_UNESCAPED_UNICODE);
}
}
function json_encrypt($str)
{
$str = trim($str,'{}');
$str = str_replace('\"',"^",$str);
$str = str_replace('"',"",$str);
$str = '['.str_replace('^','"',$str).']';
return json_decode($str,true);
}
function JSONENCODE($data){
$callback = isset($_GET['callback'])?$_GET['callback']:'';
$data = json_encode($data);
if($callback){
$data = $callback . "(". $data . ")";
}
return $data;
}
function JSONENCODEEX($data){
$callback = $_GET['callback'];
$data = json_encode_ex($data);
if($callback){
$data = $callback . "(". $data . ")";
}
return $data;
}
function json_encode_ex($value)
{
if (version_compare(PHP_VERSION,'5.4.0','<'))
{
$str = json_encode($value);
$str = preg_replace_callback(
"#\\\u([0-9a-f]{4})#i",
function( $matchs)
{
return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
},
$str
);
return $str;
}
else
{
return json_encode( $value, JSON_UNESCAPED_UNICODE);
}
}
数组处理
function arr_tree($data = [])
{
$arrdata = array();
foreach ($data as $key => $value) {
foreach ($value as $va) {
$arrdata[] = $va;
}
}
return $arrdata;
}
function arr_duplicate_removal($arr)
{
$serializeArrs = array_map('serialize', $arr);
$uniqueArrs = array_unique($serializeArrs);
$unserializeArrs = array_map('unserialize', $uniqueArrs);
return $unserializeArrs;
}
function filter_by_value($array, $index, $value)
{
$newarray = array();
if (is_array($array) && count($array) > 0) {
foreach (array_keys($array) as $key) {
$temp[$key] = $array[$key][$index];
if ($temp[$key] == $value) {
$newarray[$key] = $array[$key];
foreach ($newarray as $k => $v) {
$newarray[$k] = $v;
}
}
}
}
return $newarray;
}
function array_group($arrF,$user_count,$group_num){
for($i=0;$i<$user_count;$i++){
if($i == $user_count-1){
$arrT[] = array_slice($arrF, $i * $group_num );
}else{
$arrT[] = array_slice($arrF, $i * $group_num ,$group_num);
}
}
return $arrT;
}
function object_array($array) {
if(is_object($array)) {
$array = (array)$array;
}
if(is_array($array)) {
foreach($array as $key=>$value) {
$array[$key] = object_array($value);
}
}
return $array;
}
function group_same_key($arr,$key){
$new_arr = array();
foreach($arr as $k=>$v ){
$new_arr[$v[$key]][] = $v;
}
return $new_arr;
}
function getTree($array, $pid =0, $level = 0)
{
static $list = [];
foreach ($array as $key => $value) {
if ($value['pid'] == $pid) {
$value['level'] = $level;
$list[] = $value;
unset($array[$key]);
getTree($array, $value['id'], $level+1);
}
}
return $list;
}
地理位置相关
function get_address($ip){
$result = json_decode(file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip='.$ip.'&format=json'));
$province = isset($result->province) ? $result->province : '';
$city = isset($result->city) ? $result->city : '';
return $province.$city;
}
function getdistance($lng1,$lat1,$lng2,$lat2){
$radLat1=deg2rad((float)$lat1);
$radLat2=deg2rad((float)$lat2);
$radLng1=deg2rad((float)$lng1);
$radLng2=deg2rad((float)$lng2);
$a=$radLat1-$radLat2;
$b=$radLng1-$radLng2;
$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;
return $s;
}
function getip()
{
$clientip = '';
if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$clientip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$clientip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$clientip = getenv('REMOTE_ADDR');
} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$clientip = $_SERVER['REMOTE_ADDR'];
}
preg_match("/[\d\.]{7,15}/", $clientip, $clientipmatches);
$clientip = $clientipmatches[0] ? $clientipmatches[0] : 'unknown';
return $clientip;
}
其他
function get_rand2($proArr) {
$num = count($proArr);
for($i = 0; $i < $num; $i++) {
$arr[$i] = $i == 0 ? $proArr[$i]['v'] : $proArr[$i]['v'] + $arr[$i-1];
}
$proSum = $arr[$num-1] * 100;
$randNum = mt_rand(1, $proSum) % $arr[$num-1] + 1;
foreach ($arr as $k => $v) {
if ($randNum <= $v) {
$result = $proArr[$k];
break;
}
}
return $result;
}
|