Home >Backend Development >PHP Tutorial >Customize common PHP functions

Customize common PHP functions

不言
不言Original
2018-05-05 09:15:011333browse

这篇文章主要介绍了关于自定义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 = &#39;&#39;;
	    $string = &#39;123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ&#39;;  //数据池
	    if ($type == &#39;upper&#39;) {
	        for ($i = 0; $i < $len; $i++) {
	            $new .= $string[mt_rand(36, 61)];
	        }
	        return $new;
	    }
	    if ($type == &#39;lower&#39;) {
	        for ($i = 0; $i < $len; $i++) {
	            $new .= $string[mt_rand(10, 35)];
	        }
	        return $new;
	    }
	    if ($type == &#39;number&#39;) {
	        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(&#39;/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/&#39;, $email)){
			return false;
		}
		else{
			return true;
		}
	}

	/**
	* 正则匹配电话号码
	* @param Int $phone
	* @return Bool
	*/
	function matchPhone($phone)
	{
		if(!preg_match(&#39;/^(13[0-9]|14[5|7]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\d{8}$/&#39;, $phone)){
          	return false;
        }
        else{
        	return true;
        }
	}

	/**
	* 图片转base64
	* @param ImageFile String 图片路径
	* @return 转为base64的图片
	*/
	function Base64EncodeImage($ImageFile) {
	  if(file_exists($ImageFile) || is_file($ImageFile)){
		  $base64_image = &#39;&#39;;
		  $image_info = getimagesize($image_file);
		  $image_data = fread(fopen($image_file, &#39;r&#39;), filesize($image_file));
		  $base64_image = &#39;data:&#39; . $image_info[&#39;mime&#39;] . &#39;;base64,&#39; . 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 = &#39;utf-8&#39;;
	    if(strtolower(CHARSET)==&#39;gbk&#39;) $encoding = &#39;ISO-8859-15&#39;;
	    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 = &#39;utf-8&#39;;
	    if(strtolower(CHARSET)==&#39;gbk&#39;) $encoding = &#39;ISO-8859-15&#39;;
	    return html_entity_decode($string,ENT_QUOTES,$encoding);
	}

	/**
	 * 返回经htmlentities处理过的字符串或数组
	 * @param $string 需要处理的字符串或数组
	 * @return mixed
	 */
	function newHtmlentities($string) {
	    $encoding = &#39;utf-8&#39;;
	    if(strtolower(CHARSET)==&#39;gbk&#39;) $encoding = &#39;ISO-8859-15&#39;;
	    return htmlentities($string,ENT_QUOTES,$encoding);
	}

	/**
	 * 安全过滤函数
	 *
	 * @param $string
	 * @return string
	 */
	function safeReplace($string) {
	    $string = str_replace(&#39;%20&#39;,&#39;&#39;,$string);
	    $string = str_replace(&#39;%27&#39;,&#39;&#39;,$string);
	    $string = str_replace(&#39;%2527&#39;,&#39;&#39;,$string);
	    $string = str_replace(&#39;*&#39;,&#39;&#39;,$string);
	    $string = str_replace(&#39;"&#39;,&#39;"&#39;,$string);
	    $string = str_replace("&#39;",&#39;&#39;,$string);
	    $string = str_replace(&#39;"&#39;,&#39;&#39;,$string);
	    $string = str_replace(&#39;;&#39;,&#39;&#39;,$string);
	    $string = str_replace(&#39;<&#39;,&#39;<&#39;,$string);
	    $string = str_replace(&#39;>&#39;,&#39;>&#39;,$string);
	    $string = str_replace("{",&#39;&#39;,$string);
	    $string = str_replace(&#39;}&#39;,&#39;&#39;,$string);
	    $string = str_replace(&#39;\\&#39;,&#39;&#39;,$string);
	    return $string;
	}

	/**
	 * 过滤ASCII码从0-28的控制字符
	 * @return String
	 */
	function trimUnsafeControlChars($str) {
	    $rule = &#39;/[&#39; . chr ( 1 ) . &#39;-&#39; . chr ( 8 ) . chr ( 11 ) . &#39;-&#39; . chr ( 12 ) . chr ( 14 ) . &#39;-&#39; . chr ( 31 ) . &#39;]*/&#39;;
	    return str_replace ( chr ( 0 ), &#39;&#39;, preg_replace ( $rule, &#39;&#39;, $str ) );
	}

	/**
	 * 格式化文本域内容
	 *
	 * @param $string 文本域内容
	 * @return string
	 */
	function trimTextarea($string) {
	    $string = nl2br ( str_replace ( &#39; &#39;, &#39; &#39;, $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(&#39;&#39;, &#39;&#39;, &#39;&#39;), $string));
	    return $isjs ? &#39;document.write("&#39;.$string.&#39;");&#39; : $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 ( &#39;/\<([\/]?)script([^\>]*?)\>/si&#39;, &#39;<\\1script\\2>&#39;, $str );
	        $str = preg_replace ( &#39;/\<([\/]?)iframe([^\>]*?)\>/si&#39;, &#39;<\\1iframe\\2>&#39;, $str );
	        $str = preg_replace ( &#39;/\<([\/]?)frame([^\>]*?)\>/si&#39;, &#39;<\\1frame\\2>&#39;, $str );
	        $str = str_replace ( &#39;javascript:&#39;, &#39;javascript:&#39;, $str );
	     }
	    return $str;
	}

	/**
	 * 获取当前页面完整URL地址
	 * @return url
	 */
	function getUrl() {
	    $sys_protocal = isset($_SERVER[&#39;SERVER_PORT&#39;]) && $_SERVER[&#39;SERVER_PORT&#39;] == &#39;443&#39; ? &#39;https://&#39; : &#39;http://&#39;;
	    $php_self = $_SERVER[&#39;PHP_SELF&#39;] ? safe_replace($_SERVER[&#39;PHP_SELF&#39;]) : safe_replace($_SERVER[&#39;SCRIPT_NAME&#39;]);
	    $path_info = isset($_SERVER[&#39;PATH_INFO&#39;]) ? safe_replace($_SERVER[&#39;PATH_INFO&#39;]) : &#39;&#39;;
	    $relate_url = isset($_SERVER[&#39;REQUEST_URI&#39;]) ? safe_replace($_SERVER[&#39;REQUEST_URI&#39;]) : $php_self.(isset($_SERVER[&#39;QUERY_STRING&#39;]) ? &#39;?&#39;.safe_replace($_SERVER[&#39;QUERY_STRING&#39;]) : $path_info);
	    return $sys_protocal.(isset($_SERVER[&#39;HTTP_HOST&#39;]) ? $_SERVER[&#39;HTTP_HOST&#39;] : &#39;&#39;).$relate_url;
	}

	/**
	 * 字符截取 支持UTF8/GBK
	 * @param $string 截取的字符串
	 * @param $length 截取长度
	 * @param $dot
	 */
	function strCut($string, $length, $dot = &#39;...&#39;) {
	    $strlen = strlen($string);
	    if($strlen <= $length) return $string;
	    $string = str_replace(array(&#39; &#39;,&#39; &#39;, &#39;&&#39;, &#39;"&#39;, &#39;&#39;&#39;, &#39;“&#39;, &#39;”&#39;, &#39;—&#39;, &#39;<&#39;, &#39;>&#39;, &#39;·&#39;, &#39;…&#39;), array(&#39;∵&#39;,&#39; &#39;, &#39;&&#39;, &#39;"&#39;, "&#39;", &#39;“&#39;, &#39;”&#39;, &#39;—&#39;, &#39;<&#39;, &#39;>&#39;, &#39;·&#39;, &#39;…&#39;), $string);
	    $strcut = &#39;&#39;;
	    if(strtolower(CHARSET) == &#39;utf-8&#39;) {
	        $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(&#39;∵&#39;, &#39;&&#39;, &#39;"&#39;, "&#39;", &#39;“&#39;, &#39;”&#39;, &#39;—&#39;, &#39;<&#39;, &#39;>&#39;, &#39;·&#39;, &#39;…&#39;), array(&#39; &#39;, &#39;&&#39;, &#39;"&#39;, &#39;&#39;&#39;, &#39;“&#39;, &#39;”&#39;, &#39;—&#39;, &#39;<&#39;, &#39;>&#39;, &#39;·&#39;, &#39;…&#39;), $strcut);
	    }
	    else{
	        $dotlen = strlen($dot);
	        $maxi = $length - $dotlen - 1;
	        $current_str = &#39;&#39;;
	        $search_arr = array(&#39;&&#39;,&#39; &#39;, &#39;"&#39;, "&#39;", &#39;“&#39;, &#39;”&#39;, &#39;—&#39;, &#39;<&#39;, &#39;>&#39;, &#39;·&#39;, &#39;…&#39;,&#39;∵&#39;);
	        $replace_arr = array(&#39;&&#39;,&#39; &#39;, &#39;"&#39;, &#39;&#39;&#39;, &#39;“&#39;, &#39;”&#39;, &#39;—&#39;, &#39;<&#39;, &#39;>&#39;, &#39;·&#39;, &#39;…&#39;,&#39; &#39;);
	        $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(&#39;HTTP_CLIENT_IP&#39;) && strcasecmp(getenv(&#39;HTTP_CLIENT_IP&#39;), &#39;unknown&#39;)) {
	        $ip = getenv(&#39;HTTP_CLIENT_IP&#39;);
	    } elseif(getenv(&#39;HTTP_X_FORWARDED_FOR&#39;) && strcasecmp(getenv(&#39;HTTP_X_FORWARDED_FOR&#39;), &#39;unknown&#39;)) {
	        $ip = getenv(&#39;HTTP_X_FORWARDED_FOR&#39;);
	    } elseif(getenv(&#39;REMOTE_ADDR&#39;) && strcasecmp(getenv(&#39;REMOTE_ADDR&#39;), &#39;unknown&#39;)) {
	        $ip = getenv(&#39;REMOTE_ADDR&#39;);
	    } elseif(isset($_SERVER[&#39;REMOTE_ADDR&#39;]) && $_SERVER[&#39;REMOTE_ADDR&#39;] && strcasecmp($_SERVER[&#39;REMOTE_ADDR&#39;], &#39;unknown&#39;)) {
	        $ip = $_SERVER[&#39;REMOTE_ADDR&#39;];
	    }
	    return preg_match ( &#39;/[\d\.]{7,15}/&#39;, $ip, $matches ) ? $matches [0] : &#39;&#39;;
	}

	/**
	* 字节换算
	* @param    string    $filesize    字节大小
	* @return    string    返回大小
	*/
	function sizeCount($filesize) {
	    if ($filesize >= 1073741824) {
	        $filesize = round($filesize / 1073741824 * 100) / 100 .&#39; GB&#39;;
	    } elseif ($filesize >= 1048576) {
	        $filesize = round($filesize / 1048576 * 100) / 100 .&#39; MB&#39;;
	    } elseif($filesize >= 1024) {
	        $filesize = round($filesize / 1024 * 100) / 100 . &#39; KB&#39;;
	    } else {
	        $filesize = $filesize.&#39; Bytes&#39;;
	    }
	    return $filesize;
	}

	/**
	* 获取下个月第一天和最后一天
	* @param 上月时间
	* @return 返回下月最后一天
	*/
	function getNextMonthDays($date){
		$timestamp=strtotime($date);
		$arr=getdate($timestamp);
		if($arr[&#39;mon&#39;] == 12){
			$year=$arr[&#39;year&#39;] +1;
			$month=$arr[&#39;mon&#39;] -11;
			$firstday=$year.&#39;-0&#39;.$month.&#39;-01&#39;;
			$lastday=date(&#39;Y-m-d&#39;,strtotime("$firstday +1 month -1 day"));
		}else{
			$firstday=date(&#39;Y-m-01&#39;,strtotime(date(&#39;Y&#39;,$timestamp).&#39;-&#39;.(date(&#39;m&#39;,$timestamp)+1).&#39;-01&#39;));
			$lastday=date(&#39;Y-m-d&#39;,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 &#39;1&#39;:
	        case &#39;3&#39;:
	        case &#39;5&#39;:
	        case &#39;7&#39;:
	        case &#39;8&#39;:
	        case &#39;10&#39;:
	        case &#39;12&#39;:
	            return 31;
	        break;
	        case &#39;4&#39;:
	        case &#39;6&#39;:
	        case &#39;9&#39;:
	        case &#39;11&#39;:
	            return 30;
	        break;
	        case &#39;2&#39;:
	            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(&#39;j&#39;,strtotime($vdate));
	    $month = date(&#39;n&#39;,strtotime($vdate));
	    $year = date(&#39;Y&#39;,strtotime($vdate));
	    switch($vtype){
	        case &#39;day&#39;:
	            if($vnum >= 0){
	                $day = $day + abs($vnum);
	            }else{
	                $day = $day - abs($vnum);
	            }
	        break;
	        case &#39;month&#39;:
	            if($vnum >= 0){
	                $month = $month+ abs($vnum);
	            }else{
	                $month = $month- abs($vnum);
	            }
	            $next = getDays($month,$year);//获取变换后月份的总天数
	            if($next<$day){
	                $day = $next;
	            }
	        break;
	        case &#39;year&#39;:
	            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(&#39;Y-m-d&#39;,$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, &#39;.&#39;), 1, 10)));
	}

	/**
	 * IE浏览器判断
	 */
	function isIe() {
	    $useragent = strtolower($_SERVER[&#39;HTTP_USER_AGENT&#39;]);
	    if((strpos($useragent, &#39;opera&#39;) !== false) || (strpos($useragent, &#39;konqueror&#39;) !== false)) return false;
	    if(strpos($useragent, &#39;msie &#39;) !== false) return true;
	    return false;
	}

	/**
	 * 文件下载
	 * @param $filepath 文件路径
	 * @param $filename 文件名称
	 */
	 
	function fileDown($filepath, $filename = &#39;&#39;) {
	    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(&#39;Pragma: public&#39;);
	    header(&#39;Last-Modified: &#39;.gmdate(&#39;D, d M Y H:i:s&#39;) . &#39; GMT&#39;);
	    header(&#39;Cache-Control: no-store, no-cache, must-revalidate&#39;);
	    header(&#39;Cache-Control: pre-check=0, post-check=0, max-age=0&#39;);
	    header(&#39;Content-Transfer-Encoding: binary&#39;);
	    header(&#39;Content-Encoding: none&#39;);
	    header(&#39;Content-type: &#39;.$filetype);
	    header(&#39;Content-Disposition: attachment; filename="&#39;.$filename.&#39;"&#39;);
	    header(&#39;Content-length: &#39;.$filesize);
	    readfile($filepath);
	    exit;
	}

	/**
	 * 判断字符串是否为utf8编码,英文和半角字符返回ture
	 * @param $string
	 * @return bool
	 */
	function isUtf8($string) {
	    return preg_match(&#39;%^(?:
	                    [\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&#39;, $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("\\",&#39;&&#39;,&#39; &#39;,"&#39;",&#39;"&#39;,&#39;/&#39;,&#39;*&#39;,&#39;,&#39;,&#39;<&#39;,&#39;>&#39;,"\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 = &#39;gbk&#39;, $output = &#39;utf-8&#39;) {
	    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(&#39;http&#39; => array(&#39;timeout&#39; => $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 = &#39;00&#39; . time() . rand(1000, 9999); //00 本地订单
	    }
	    else {
	        $str = &#39;99&#39; . 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 = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\.|\/|\;|\&#39;|\`|\=|\\\|\|/";
	    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[&#39;HTTP_X_WAP_PROFILE&#39;]))
        {
            return true;
        } 
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER[&#39;HTTP_VIA&#39;]))
        { 
            // 找不到为flase,否则为true
            return stristr($_SERVER[&#39;HTTP_VIA&#39;], "wap") ? true : false;
        } 
        // 脑残法,判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER[&#39;HTTP_USER_AGENT&#39;]))
        {
            $clientkeywords = array (&#39;nokia&#39;,
                &#39;sony&#39;,
                &#39;ericsson&#39;,
                &#39;mot&#39;,
                &#39;samsung&#39;,
                &#39;htc&#39;,
                &#39;sgh&#39;,
                &#39;lg&#39;,
                &#39;sharp&#39;,
                &#39;sie-&#39;,
                &#39;philips&#39;,
                &#39;panasonic&#39;,
                &#39;alcatel&#39;,
                &#39;lenovo&#39;,
                &#39;iphone&#39;,
                &#39;ipod&#39;,
                &#39;blackberry&#39;,
                &#39;meizu&#39;,
                &#39;android&#39;,
                &#39;netfront&#39;,
                &#39;symbian&#39;,
                &#39;ucweb&#39;,
                &#39;windowsce&#39;,
                &#39;palm&#39;,
                &#39;operamini&#39;,
                &#39;operamobi&#39;,
                &#39;openwave&#39;,
                &#39;nexusone&#39;,
                &#39;cldc&#39;,
                &#39;midp&#39;,
                &#39;wap&#39;,
                &#39;mobile&#39;
                ); 
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode(&#39;|&#39;, $clientkeywords) . ")/i", strtolower($_SERVER[&#39;HTTP_USER_AGENT&#39;])))
            {
                return true;
            } 
        } 
        // 协议法,因为有可能不准确,放到最后判断
        if (isset ($_SERVER[&#39;HTTP_ACCEPT&#39;]))
        { 
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER[&#39;HTTP_ACCEPT&#39;], &#39;vnd.wap.wml&#39;) !== false) && (strpos($_SERVER[&#39;HTTP_ACCEPT&#39;], &#39;text/html&#39;) === false || (strpos($_SERVER[&#39;HTTP_ACCEPT&#39;], &#39;vnd.wap.wml&#39;) < strpos($_SERVER[&#39;HTTP_ACCEPT&#39;], &#39;text/html&#39;))))
            {
                return true;
            } 
        } 
        return false;
    }

    /**
    * 判断是否为安卓手机
    */
    function isAndroid()
    {
        if(isset($_SERVER[&#39;HTTP_USER_AGENT&#39;])){
            $agent = strtolower($_SERVER[&#39;HTTP_USER_AGENT&#39;]);
            if(strpos($agent,&#39;android&#39;) !== false)
                return true;
        }
        return false;
    }

    /**
    * 判断是否为iphone或者ipad
    */
    function isIos()
    {
        if(isset($_SERVER[&#39;HTTP_USER_AGENT&#39;])){
            $agent = strtolower($_SERVER[&#39;HTTP_USER_AGENT&#39;]);
            if(strpos($agent, &#39;iphone&#39;)||strpos($agent, &#39;ipad&#39;))
                return true;
        }
        return false;
    }

    /**
    * 判断是否是微信浏览器还是企业微信浏览器
    */
    function isWxbrowser()
    {
    	if ( strpos($_SERVER[&#39;HTTP_USER_AGENT&#39;], &#39;MicroMessenger&#39;) !== false ) {  
        	return true;  
	    }  
	    else{  
	        return false;  
	    }
    }
    /**
    * 判断是否是企业微信浏览器
    */
    function isWxCompany()
    {
    	if( strpos($_SERVER[&#39;HTTP_USER_AGENT&#39;], &#39;wxwork&#39;) !== false ) {  
        	return true;  
	    }  
	    else{  
	        return false;  
	    } 
    }

    /**
    * 整合到一起,判断当前设备,1:安卓;2:IOS;3:微信;0:未知
    */
    function isDevice()
    {
        if($_SERVER[&#39;HTTP_USER_AGENT&#39;]){
            $agent = strtolower($_SERVER[&#39;HTTP_USER_AGENT&#39;]);
            if(strpos($agent, &#39;micromessenger&#39;) !== false)
                return 3;
            elseif(strpos($agent, &#39;iphone&#39;)||strpos($agent, &#39;ipad&#39;))
                return 2;
            else
                return 1;
        }
        return 0;
    }

    /**
     * 日期转换成几分钟前
     */
    function formatTime($date) {
        $timer = strtotime($date);
        $diff = $_SERVER[&#39;REQUEST_TIME&#39;] - $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 &#39;刚刚&#39;;
                        }
                    }
                    }else{
                        return &#39;刚刚&#39;;
                    }
                }
            }else{
                return &#39;刚刚&#39;;
            }
        }
    }

    /**
    * 字符串截取
    * @param String 被截取的字符串
    * @param Int 	截取长度
    */
	function getStrTruncate($string, $length = &#39;&#39;, $etc = &#39;&#39;){
		  if ($length == 0) return &#39;&#39;;
		  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=&#39;&#39;; $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 == &#39;.&#39; || $file == &#39;..&#39;)
	           {
	               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(&#39;/select|insert|update|delete|\&#39;|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/&#39;, $sql_str); 
	    if ($check) { 
	        echo &#39;非法字符!!&#39;; 
	        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[&#39;access&#39;] = in_array($v[&#39;id&#39;],$arr) ? 1: 0;
	        }
	    }
	    return $attr;
	}

	/**
	 * 获取文件信息
	 * @param string $filepath 路径
	 * @param string $key 指定返回某个键值信息
	 * @return array
	 */
	function get_file_info($filepath=&#39;&#39;, $key=&#39;&#39;){
	    //打开文件,r表示以只读方式打开
	    $handle = fopen($filepath,"r");
	    //获取文件的统计信息
	    $fstat = fstat($handle);
	 
	    fclose($handle);
	    $fstat[&#39;filename&#39;] = 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=&#39;asc&#39;) {
	   if(is_array($list)){
	       $refer = $resultSet = array();
	       foreach ($list as $i => $data)
	           $refer[$i] = &$data[$field];
	       switch ($sortby) {
	           case &#39;asc&#39;: // 正向排序
	                asort($refer);
	                break;
	           case &#39;desc&#39;:// 逆向排序
	                arsort($refer);
	                break;
	           case &#39;nat&#39;: // 自然排序
	                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=&#39;id&#39;, $pid = &#39;pid&#39;, $child = &#39;_child&#39;, $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 = &#39;_child&#39;, $order=&#39;id&#39;, &$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=&#39;asc&#39;);
	    }
	    return $list;
	}

相关推荐:

自定义PHP的错误报告处理方式



The above is the detailed content of Customize common PHP functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP function quick checkNext article:PHP function quick check