这篇文章主要介绍了关于自定义php常用功能函数,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
<?php
// +----------------------------------------------------------------------
// | php公共函数库
// +----------------------------------------------------------------------
// | date : 2018-05-04
// +----------------------------------------------------------------------
// | create by: sublime text 3
// +----------------------------------------------------------------------
// | author: deng <xiaolower@qq.com>
// +----------------------------------------------------------------------
/**
* 预定义常量
*/
define("charset", "utf-8");
/**
* 冒泡排序
* @param array 排序数组
* @return array 排序号的数组
*/
function bubblesort($arr)
{
$len=count($arr);
//该层循环控制 需要冒泡的轮数
for($i=1;$i<$len;$i++)
{ //该层循环用来控制每轮 冒出一个数 需要比较的次数
for($k=0;$k<$len-$i;$k++)
{
if($arr[$k]>$arr[$k+1])
{
$tmp=$arr[$k+1];
$arr[$k+1]=$arr[$k];
$arr[$k]=$tmp;
}
}
}
return $arr;
}
/**
* 选择排序
* @param array
* @return array
*/
function selectsort($arr) {
//双重循环完成,外层控制轮数,内层控制比较次数
$len=count($arr);
for($i=0; $i<$len-1; $i++) {
//先假设最小的值的位置
$p = $i;
for($j=$i+1; $j<$len; $j++) {
//$arr[$p] 是当前已知的最小值
if($arr[$p] > $arr[$j]) {
//比较,发现更小的,记录下最小值的位置;并且在下次比较时采用已知的最小值进行比较。
$p = $j;
}
}
//已经确定了当前的最小值的位置,保存到$p中。如果发现最小值的位置与当前假设的位置$i不同,则位置互换即可。
if($p != $i) {
$tmp = $arr[$p];
$arr[$p] = $arr[$i];
$arr[$i] = $tmp;
}
}
//返回最终结果
return $arr;
}
/**
* 插入排序
* @param array
* @return array
*/
function insertsort($arr) {
$len=count($arr);
for($i=1; $i<$len; $i++) {
$tmp = $arr[$i];
//内层循环控制,比较并插入
for($j=$i-1;$j>=0;$j--) {
if($tmp < $arr[$j]) {
//发现插入的元素要小,交换位置,将后边的元素与前面的元素互换
$arr[$j+1] = $arr[$j];
$arr[$j] = $tmp;
}
else {
//如果碰到不需要移动的元素,由于是已经排序好是数组,则前面的就不需要再次比较了。
break;
}
}
}
return $arr;
}
/**
* 快速排序
* @param array
* @return array
*/
function quicksort($arr) {
//先判断是否需要继续进行
$length = count($arr);
if($length <= 1) {
return $arr;
}
//选择第一个元素作为基准
$base_num = $arr[0];
//遍历除了标尺外的所有元素,按照大小关系放入两个数组内
//初始化两个数组
$left_array = array(); //小于基准的
$right_array = array(); //大于基准的
for($i=1; $i<$length; $i++) {
if($base_num > $arr[$i]) {
//放入左边数组
$left_array[] = $arr[$i];
}
else{
//放入右边
$right_array[] = $arr[$i];
}
}
//再分别对左边和右边的数组进行相同的排序处理方式递归调用这个函数
$left_array = quick_sort($left_array);
$right_array = quick_sort($right_array);
//合并
return array_merge($left_array, array($base_num), $right_array);
}
/**
* 随机生成几位数字
* @param $num int
* @return int
*/
function randomint($num){
if(is_null($num) || empty($num) || !isset($num)){
$num = 6;
}
else{
$param = str_pad(mt_rand(0, 999999), $num, "0", str_pad_both);// 返回 input 被从左端、右端或者同时两端被填充到制定长度后的结果。如果可选的 pad_string 参数没有被指定,input 将被空格字符填充,否则它将被 pad_string 填充到指定长度
}
return $param;
}
/**
* 生成随机字符串,可以自己扩展 //若想唯一,只需在开头加上用户id
* $type可以为:upper(只生成大写字母),lower(只生成小写字母),number(只生成数字)
* $len为长度,定义字符串长度
* @param $len int 指定字符串长度
* @param $type 类型
* @param return 随机字符串
*/
function randomstring($type, $len = 0) {
$new = '';
$string = '123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnpqrstuvwxyz'; //数据池
if ($type == 'upper') {
for ($i = 0; $i < $len; $i++) {
$new .= $string[mt_rand(36, 61)];
}
return $new;
}
if ($type == 'lower') {
for ($i = 0; $i < $len; $i++) {
$new .= $string[mt_rand(10, 35)];
}
return $new;
}
if ($type == 'number') {
for ($i = 0; $i < $len; $i++) {
$new .= $string[mt_rand(0, 9)];
}
return $new;
}
}
/**
* 正则验证邮箱地址
* @param $email string
* @return bool
*/
function matchemail($email){
if(!preg_match('/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/', $email)){
return false;
}
else{
return true;
}
}
/**
* 正则匹配电话号码
* @param int $phone
* @return bool
*/
function matchphone($phone)
{
if(!preg_match('/^(13[0-9]|14[5|7]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\d{8}$/', $phone)){
return false;
}
else{
return true;
}
}
/**
* 图片转base64
* @param imagefile string 图片路径
* @return 转为base64的图片
*/
function base64encodeimage($imagefile) {
if(file_exists($imagefile) || is_file($imagefile)){
$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 $base64_image;
}
else{
return false;
}
}
/**
* 返回经addslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function newaddslashes($string){
if(!is_array($string)) return addslashes($string);
foreach($string as $key => $val) $string[$key] = new_addslashes($val);
return $string;
}
/**
* 返回经stripslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function newstripslashes($string) {
if(!is_array($string)) return stripslashes($string);
foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
return $string;
}
/**
* 返回经htmlspecialchars处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function newhtmlspecialchars($string) {
$encoding = 'utf-8';
if(strtolower(charset)=='gbk') $encoding = 'iso-8859-15';
if(!is_array($string)) return htmlspecialchars($string,ent_quotes,$encoding);
foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
return $string;
}
/**
* 返回经html_entity_decode处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function newhtmleentityddecode($string) {
$encoding = 'utf-8';
if(strtolower(charset)=='gbk') $encoding = 'iso-8859-15';
return html_entity_decode($string,ent_quotes,$encoding);
}
/**
* 返回经htmlentities处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function newhtmlentities($string) {
$encoding = 'utf-8';
if(strtolower(charset)=='gbk') $encoding = 'iso-8859-15';
return htmlentities($string,ent_quotes,$encoding);
}
/**
* 安全过滤函数
*
* @param $string
* @return string
*/
function safereplace($string) {
$string = str_replace('%20','',$string);
$string = str_replace('%27','',$string);
$string = str_replace('%2527','',$string);
$string = str_replace('*','',$string);
$string = str_replace('"','"',$string);
$string = str_replace("'",'',$string);
$string = str_replace('"','',$string);
$string = str_replace(';','',$string);
$string = str_replace('<','<',$string);
$string = str_replace('>','>',$string);
$string = str_replace("{",'',$string);
$string = str_replace('}','',$string);
$string = str_replace('\\','',$string);
return $string;
}
/**
* 过滤ascii码从0-28的控制字符
* @return string
*/
function trimunsafecontrolchars($str) {
$rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
}
/**
* 格式化文本域内容
*
* @param $string 文本域内容
* @return string
*/
function trimtextarea($string) {
$string = nl2br ( str_replace ( ' ', ' ', $string ) );
return $string;
}
/**
* 将文本格式成适合js输出的字符串
* @param string $string 需要处理的字符串
* @param intval $isjs 是否执行字符串格式化,默认为执行
* @return string 处理后的字符串
*/
function formatjs($string, $isjs = 1) {
$string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
return $isjs ? 'document.write("'.$string.'");' : $string;
}
/**
* 转义 javascript 代码标记
*
* @param $str
* @return mixed
*/
function trimscript($str) {
if(is_array($str)){
foreach ($str as $key => $val){
$str[$key] = trim_script($val);
}
}
else{
$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '<\\1script\\2>', $str );
$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '<\\1iframe\\2>', $str );
$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '<\\1frame\\2>', $str );
$str = str_replace ( 'javascript:', 'javascript:', $str );
}
return $str;
}
/**
* 获取当前页面完整url地址
* @return url
*/
function geturl() {
$sys_protocal = isset($_server['server_port']) && $_server['server_port'] == '443' ? 'https://' : 'http://';
$php_self = $_server['php_self'] ? safe_replace($_server['php_self']) : safe_replace($_server['script_name']);
$path_info = isset($_server['path_info']) ? safe_replace($_server['path_info']) : '';
$relate_url = isset($_server['request_uri']) ? safe_replace($_server['request_uri']) : $php_self.(isset($_server['query_string']) ? '?'.safe_replace($_server['query_string']) : $path_info);
return $sys_protocal.(isset($_server['http_host']) ? $_server['http_host'] : '').$relate_url;
}
/**
* 字符截取 支持utf8/gbk
* @param $string 截取的字符串
* @param $length 截取长度
* @param $dot
*/
function strcut($string, $length, $dot = '...') {
$strlen = strlen($string);
if($strlen <= $length) return $string;
$string = str_replace(array(' ',' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
$strcut = '';
if(strtolower(charset) == 'utf-8') {
$length = intval($length-strlen($dot)-$length/3);
$n = $tn = $noc = 0;
while($n < strlen($string)) {
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; $n++; $noc++;
} elseif(194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 2;
} elseif(224 <= $t && $t <= 239) {
$tn = 3; $n += 3; $noc += 2;
} elseif(240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 2;
} elseif(248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 2;
} elseif($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 2;
} else {
$n++;
}
if($noc >= $length) {
break;
}
}
if($noc > $length) {
$n -= $tn;
}
$strcut = substr($string, 0, $n);
$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), $strcut);
}
else{
$dotlen = strlen($dot);
$maxi = $length - $dotlen - 1;
$current_str = '';
$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
$replace_arr = array('&',' ', '"', ''', '“', '”', '—', '<', '>', '·', '…',' ');
$search_flip = array_flip($search_arr);
for ($i = 0; $i < $maxi; $i++) {
$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
if (in_array($current_str, $search_arr)) {
$key = $search_flip[$current_str];
$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
}
$strcut .= $current_str;
}
}
return $strcut.$dot;
}
/**
* 获取请求ip
* @return ip地址
*/
function getip() {
if(getenv('http_client_ip') && strcasecmp(getenv('http_client_ip'), 'unknown')) {
$ip = getenv('http_client_ip');
} elseif(getenv('http_x_forwarded_for') && strcasecmp(getenv('http_x_forwarded_for'), 'unknown')) {
$ip = getenv('http_x_forwarded_for');
} elseif(getenv('remote_addr') && strcasecmp(getenv('remote_addr'), 'unknown')) {
$ip = getenv('remote_addr');
} elseif(isset($_server['remote_addr']) && $_server['remote_addr'] && strcasecmp($_server['remote_addr'], 'unknown')) {
$ip = $_server['remote_addr'];
}
return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}
/**
* 字节换算
* @param string $filesize 字节大小
* @return string 返回大小
*/
function sizecount($filesize) {
if ($filesize >= 1073741824) {
$filesize = round($filesize / 1073741824 * 100) / 100 .' gb';
} elseif ($filesize >= 1048576) {
$filesize = round($filesize / 1048576 * 100) / 100 .' mb';
} elseif($filesize >= 1024) {
$filesize = round($filesize / 1024 * 100) / 100 . ' kb';
} else {
$filesize = $filesize.' bytes';
}
return $filesize;
}
/**
* 获取下个月第一天和最后一天
* @param 上月时间
* @return 返回下月最后一天
*/
function getnextmonthdays($date){
$timestamp=strtotime($date);
$arr=getdate($timestamp);
if($arr['mon'] == 12){
$year=$arr['year'] +1;
$month=$arr['mon'] -11;
$firstday=$year.'-0'.$month.'-01';
$lastday=date('y-m-d',strtotime("$firstday +1 month -1 day"));
}else{
$firstday=date('y-m-01',strtotime(date('y',$timestamp).'-'.(date('m',$timestamp)+1).'-01'));
$lastday=date('y-m-d',strtotime("$firstday +1 month -1 day"));
}
return array($firstday,$lastday);
}
/**
* 获取给定月份的天数
* @param int $month 需要获取天数的月份
* @param int $year 需要获取天数的年份
* @return int 天数
*/
function getdays($month,$year){
switch($month){
case '1':
case '3':
case '5':
case '7':
case '8':
case '10':
case '12':
return 31;
break;
case '4':
case '6':
case '9':
case '11':
return 30;
break;
case '2':
if(($year%4==0 && $year%100!=0) || $year%400==0){//整百的年份要同时满足400的倍数才算闰年
return 29;
}else{
return 28;
}
break;
}
}
/**
* 获取指定日期的前/后多少天,月,年
* @param date $vdate 指定的日期
* @param int $num 向前还是向后
* @param string $vtype 天/月/年
* @return date 获取的时间
*/
function datecount($vdate,$vnum,$vtype){
$day = date('j',strtotime($vdate));
$month = date('n',strtotime($vdate));
$year = date('y',strtotime($vdate));
switch($vtype){
case 'day':
if($vnum >= 0){
$day = $day + abs($vnum);
}else{
$day = $day - abs($vnum);
}
break;
case 'month':
if($vnum >= 0){
$month = $month+ abs($vnum);
}else{
$month = $month- abs($vnum);
}
$next = getdays($month,$year);//获取变换后月份的总天数
if($next<$day){
$day = $next;
}
break;
case 'year':
if($vnum >= 0){
$year = $year+ abs($vnum);
}else{
$year = $year - abs($vnum);
}
break;
default :
break;
}
$time = mktime(0,0,0,$month,$day,$year);
return date('y-m-d',$time);
}
/**
* 查询字符是否存在于某字符串
* @param $haystack 字符串
* @param $needle 要查找的字符
* @return bool
*/
function strexists($haystack, $needle){
return !(strpos($haystack, $needle) === false);
}
/**
* 取得文件扩展
* @param $filename 文件名
* @return 扩展名
*/
function fileext($filename) {
return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}
/**
* ie浏览器判断
*/
function isie() {
$useragent = strtolower($_server['http_user_agent']);
if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
if(strpos($useragent, 'msie ') !== false) return true;
return false;
}
/**
* 文件下载
* @param $filepath 文件路径
* @param $filename 文件名称
*/
function filedown($filepath, $filename = '') {
if(!$filename) $filename = basename($filepath);
if(is_ie()) $filename = rawurlencode($filename);
$filetype = fileext($filename);
$filesize = sprintf("%u", filesize($filepath));
if(ob_get_length() !== false) @ob_end_clean();
header('pragma: public');
header('last-modified: '.gmdate('d, d m y h:i:s') . ' gmt');
header('cache-control: no-store, no-cache, must-revalidate');
header('cache-control: pre-check=0, post-check=0, max-age=0');
header('content-transfer-encoding: binary');
header('content-encoding: none');
header('content-type: '.$filetype);
header('content-disposition: attachment; filename="'.$filename.'"');
header('content-length: '.$filesize);
readfile($filepath);
exit;
}
/**
* 判断字符串是否为utf8编码,英文和半角字符返回ture
* @param $string
* @return bool
*/
function isutf8($string) {
return preg_match('%^(?:
[\x09\x0a\x0d\x20-\x7e] # ascii
| [\xc2-\xdf][\x80-\xbf] # non-overlong 2-byte
| \xe0[\xa0-\xbf][\x80-\xbf] # excluding overlongs
| [\xe1-\xec\xee\xef][\x80-\xbf]{2} # straight 3-byte
| \xed[\x80-\x9f][\x80-\xbf] # excluding surrogates
| \xf0[\x90-\xbf][\x80-\xbf]{2} # planes 1-3
| [\xf1-\xf3][\x80-\xbf]{3} # planes 4-15
| \xf4[\x80-\x8f][\x80-\xbf]{2} # plane 16
)*$%xs', $string);
}
/**
* 检查密码长度是否符合规定
*
* @param string $password
* @return true or false
*/
function ispassword($password) {
$strlen = strlen($password);
if($strlen >= 6 && $strlen <= 20) return true;
return false;
}
/**
* 检测输入中是否含有特殊字符
*
* @param char $string 要检查的字符串名称
* @return true or false
*/
function isbadword($string) {
$badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");
foreach($badwords as $value){
if(strpos($string, $value) !== false) {
return true;
}
}
return false;
}
/**
* 检查用户名是否符合规定
*
* @param string $username 要检查的用户名
* @return true or false
*/
function isusername($username) {
$strlen = strlen($username);
if(is_badword($username) || !preg_match("/^[a-za-z0-9_\x7f-\xff][a-za-z0-9_\x7f-\xff]+$/", $username)){
return false;
}
elseif ( 20 < $strlen || $strlen < 2 ) {
return false;
}
return true;
}
/**
* 对数据进行编码转换
* @param array/string $data 数组
* @param string $input 需要转换的编码
* @param string $output 转换后的编码
*/
function arrayiconv($data, $input = 'gbk', $output = 'utf-8') {
if (!is_array($data)) {
return iconv($input, $output, $data);
}
else{
foreach ($data as $key=>$val) {
if(is_array($val)) {
$data[$key] = array_iconv($val, $input, $output);
} else {
$data[$key] = iconv($input, $output, $val);
}
}
return $data;
}
}
/**
*
* 抓取远程内容
* @param $url 接口url地址
* @param $timeout 超时时间
*/
function pcfilegetcontents($url, $timeout=30) {
$stream = stream_context_create(array('http' => array('timeout' => $timeout)));
return @file_get_contents($url, 0, $stream);
}
/**
* function dataformat
* 时间转换
* @param $n int时间
*/
function dataformat($n) {
$hours = floor($n/3600);
$minite = floor($n%3600/60);
$secend = floor($n%3600%60);
$minite = $minite < 10 ? "0".$minite : $minite;
$secend = $secend < 10 ? "0".$secend : $secend;
if($n >= 3600){
return $hours.":".$minite.":".$secend;
}else{
return $minite.":".$secend;
}
}
/**
* 生成订单15位
*/
function setuporder($ord = 0) {
//自动生成订单号 传入参数为0 或者1 0为本地 1为线上订单
if ($ord == 0) {
$str = '00' . time() . rand(1000, 9999); //00 本地订单
}
else {
$str = '99' . time() . rand(1000, 9999); //11 线上订单
}
return $str;
}
/**
* 处理json字符中的特殊字符
* @param 需要处理的json php > 5.2 json_encode 知道转义
*/
function getjsontoarr($value) {
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
/**
* 非法字符过滤函数
* @param 过滤字符串
*/
function hasunsafeword($str) {
$regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\.|\/|\;|\'|\`|\=|\\\|\|/";
return preg_replace($regex,"",$str);
}
/**
* 去空格,以及字符添加斜杠
*/
function cleartrim(&$value) {
return addslashes(trim($value));
}
/**
* 数组降维
* @param array $arr
* @return array
*/
function arrmd2ud($arr) {
#将数值第一元素作为容器,作地址赋值。
$ar_room = &$arr[key($arr)];
#第一容器不是数组进去转呀
if (!is_array($ar_room)) {
#转为成数组
$ar_room = array($ar_room);
}
#指针下移
next($arr);
#遍历
while (list($k, $v) = each($arr)) {
#是数组就递归深挖,不是就转成数组
$v = is_array($v) ? call_user_func(__function__, $v) : array($v);
#递归合并
$ar_room = array_merge_recursive($ar_room, $v);
#释放当前下标的数组元素
unset($arr[$k]);
}
return $ar_room;
}
/**
* 判断是pc端还是wap端访问
* @return type判断手机移动设备访问
*/
function ismobile()
{
// 如果有http_x_wap_profile则一定是移动设备
if (isset ($_server['http_x_wap_profile']))
{
return true;
}
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset ($_server['http_via']))
{
// 找不到为flase,否则为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;
}
/**
* 判断是否为安卓手机
*/
function isandroid()
{
if(isset($_server['http_user_agent'])){
$agent = strtolower($_server['http_user_agent']);
if(strpos($agent,'android') !== false)
return true;
}
return false;
}
/**
* 判断是否为iphone或者ipad
*/
function isios()
{
if(isset($_server['http_user_agent'])){
$agent = strtolower($_server['http_user_agent']);
if(strpos($agent, 'iphone')||strpos($agent, 'ipad'))
return true;
}
return false;
}
/**
* 判断是否是微信浏览器还是企业微信浏览器
*/
function iswxbrowser()
{
if ( strpos($_server['http_user_agent'], 'micromessenger') !== false ) {
return true;
}
else{
return false;
}
}
/**
* 判断是否是企业微信浏览器
*/
function iswxcompany()
{
if( strpos($_server['http_user_agent'], 'wxwork') !== false ) {
return true;
}
else{
return false;
}
}
/**
* 整合到一起,判断当前设备,1:安卓;2:ios;3:微信;0:未知
*/
function isdevice()
{
if($_server['http_user_agent']){
$agent = strtolower($_server['http_user_agent']);
if(strpos($agent, 'micromessenger') !== false)
return 3;
elseif(strpos($agent, 'iphone')||strpos($agent, 'ipad'))
return 2;
else
return 1;
}
return 0;
}
/**
* 日期转换成几分钟前
*/
function formattime($date) {
$timer = strtotime($date);
$diff = $_server['request_time'] - $timer;
$day = floor($diff / 86400);
$free = $diff % 86400;
if($day > 0) {
if(15 < $day && $day <30){
return "半个月前";
}elseif(30 <= $day && $day <90){
return "1个月前";
}elseif(90 <= $day && $day <187){
return "3个月前";
}elseif(187 <= $day && $day <365){
return "半年前";
}elseif(365 <= $day){
return "1年前";
}else{
return $day."天前";
}
}else{
if($free>0){
$hour = floor($free / 3600);
$free = $free % 3600;
if($hour>0){
return $hour."小时前";
}else{
if($free>0){
$min = floor($free / 60);
$free = $free % 60;
if($min>0){
return $min."分钟前";
}else{
if($free>0){
return $free."秒前";
}else{
return '刚刚';
}
}
}else{
return '刚刚';
}
}
}else{
return '刚刚';
}
}
}
/**
* 字符串截取
* @param string 被截取的字符串
* @param int 截取长度
*/
function getstrtruncate($string, $length = '', $etc = ''){
if ($length == 0) return '';
mb_internal_encoding("utf-8");
$string = str_replace("\n","",$string);
$strlen = mb_strwidth($string);
if ($strlen > $length) {
$etclen = mb_strwidth($etc);
$length = $length - $etclen;
$str=''; $n = 0;
for($i=0; $i<$length; $i++) {
$c = mb_substr($string, $i, 1);
$n += mb_strwidth($c);
if ($n>$length) { break; }
$str .= $c;
}
return $str.$etc;
}
else{
return $string;
}
}
/**
* 删除目录 比如缓存
* @param $dir 目录
*/
function destroydir($dir, $virtual = false){
$ds = directory_separator;
$dir = $virtual ? realpath($dir) : $dir;
$dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
if (is_dir($dir) && $handle = opendir($dir))
{
while ($file = readdir($handle))
{
if ($file == '.' || $file == '..')
{
continue;
}
elseif (is_dir($dir.$ds.$file)){
destroydir($dir.$ds.$file);
}
else{
unlink($dir.$ds.$file);
}
}
closedir($handle);
rmdir($dir);
return true;
}
else{
return false;
}
}
/**
* 防sql 注入
*/
function injcheck($sql_str) {
$check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);
if ($check) {
echo '非法字符!!';
exit;
}
else{
return $sql_str;
}
}
/**
* 对象转数组
*/
function objecttoarray($obj){
$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($_arr as $key => $val){
$val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
$arr[$key] = $val;
}
return $arr;
}
/**
* 判断两个字符串是否相等
*/
function stringequal($str1,$str2){
if(strcmp($str1,$str2) == 0){
return true;
}
else{
return false;
}
}
/**
* 递归重组信息为多维
* @param string $dirname 路径
* @param boolean $fileflag 是否删除目录
* @return void
*/
function nodemerge($attr, $arr) {
foreach($attr as $v){
if (is_array($arr)){
$v['access'] = in_array($v['id'],$arr) ? 1: 0;
}
}
return $attr;
}
/**
* 获取文件信息
* @param string $filepath 路径
* @param string $key 指定返回某个键值信息
* @return array
*/
function get_file_info($filepath='', $key=''){
//打开文件,r表示以只读方式打开
$handle = fopen($filepath,"r");
//获取文件的统计信息
$fstat = fstat($handle);
fclose($handle);
$fstat['filename'] = basename($filepath);
if(!empty($key)){
return $fstat[$key];
}else{
return $fstat;
}
}
/**
* 对查询结果集进行排序
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
* @return array
*/
function listsortby($list,$field, $sortby='asc') {
if(is_array($list)){
$refer = $resultset = array();
foreach ($list as $i => $data)
$refer[$i] = &$data[$field];
switch ($sortby) {
case 'asc': // 正向排序
asort($refer);
break;
case 'desc':// 逆向排序
arsort($refer);
break;
case 'nat': // 自然排序
natcasesort($refer);
break;
}
foreach ( $refer as $key=> $val)
$resultset[] = &$list[$key];
return $resultset;
}
return false;
}
/**
* 把返回的数据集转换成tree
* @param array $list 要转换的数据集
* @param string $pid parent标记字段
* @param string $level level标记字段
* @return array
*/
function listtotree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
// 创建tree
$tree = array();
if(is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $val) {
$refer[$val[$pk]] =& $list[$key];
}
foreach ($list as $key => $val) {
// 判断是否存在parent
$parentid = $val[$pid];
if ($root == $parentid) {
$tree[] =& $list[$key];
}else{
if (isset($refer[$parentid])) {
$parent =& $refer[$parentid];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
/**
* 将list_to_tree的树还原成列表
* @param array $tree 原来的树
* @param string $child 孩子节点的键
* @param string $order 排序显示的键,一般是主键 升序排列
* @param array $list 过渡用的中间数组,
* @return array 返回排过序的列表数组
*/
function treetolist($tree, $child = '_child', $order='id', &$list = array()){
if(is_array($tree)) {
$refer = array();
foreach ($tree as $key => $value) {
$reffer = $value;
if(isset($reffer[$child])){
unset($reffer[$child]);
tree_to_list($value[$child], $child, $order, $list);
}
$list[] = $reffer;
}
$list = list_sort_by($list, $order, $sortby='asc');
}
return $list;
}
相关推荐:
自定义php的错误报告处理方式
以上就是自定义php常用功能函数的详细内容。