zoukankan      html  css  js  c++  java
  • php常用自定义函数

    根据请求url获取xml结果并转换成json对象

    /**
    * 根据请求url获取xml结果并转换成json对象
    * @author ganyuanjiang  <3164145970@qq.com>
    * @time 2017-07-26 13:25:56
    * @param 
    * @return json mixed
    */
    
    if (!function_exists('xml_json')) {
    
        function xml_json($url)
        {
            $res = json_decode(json_encode(simplexml_load_string(file_get_contents($url))),true);
            return $res;
        }
    }

    根据请求url获取字符串数组结果并转换成json对象

    /**
    * 根据请求url获取字符串数组结果并转换成json对象
    * @author ganyuanjiang  <3164145970@qq.com>
    * @time 2017-07-26 13:29:12
    * @param url 请求链接
    * @return json mixed
    */
    
    if (!function_exists('string_json')) {
    
        function string_json($url)
        {
            $arrContextOptions=array(
              "ssl"=>array(
                  "verify_peer"=>false,
                  "verify_peer_name"=>false,
              ),
            );  
            $res = json_decode(file_get_contents($url, false, stream_context_create($arrContextOptions)),true);
            return $res;
        }
    }

    将数组转换成xml

    /**
    * 将数组转换成xml
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-08-31 16:04:13
    * @return xml
    */
    if(!function_exists('arr_xml')){
       function arr_xml($arr)
      {
        if(!is_array($arr) || count($arr) <= 0)
        {
            return false;
        }
          
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
          if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
          }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
          }
        }
          $xml.="</xml>";
          return $xml; 
      }
    }

    将xml转为array

    /**
    * 将xml转为array
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-09-11 10:31:31
    * @param string $xml
    * @return array
    */
    if(!function_exists('xml_arr')){
       function xml_arr($xml)
      {
        if(!$xml){
          return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);    
        return $result;
      }
    }

    ajax请求返回函数

    /**ajax请求返回函数
     * @param int $code 错误代码
     * @param string $msg 错误或成功消息
     * @param array $arr json资源
     * @return array 数组,tp5自动转换json
     */function json_result($code,$msg="",$arr=array()){
        header("Content-type: text/html; charset=utf-8");
        header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
        header("Access-Control-Allow-origin: *");
        header("Access-Control-Allow-Headers: X-Requested-With");
        header("Access-Control-Allow-Methods: POST,GET");
        $result=array();
        $result['error_code']=$code;
        $result['msg']=$msg;
        $result['res']=$arr;
        echo json_encode($result);
    }

    获取json数据

    /**获取json数据
     * @param $uid 用户主键id
     * @param $salt 用户盐值
     * @return string token字符串
     */
    function get_JsonData(){
        $json = file_get_contents('php://input');
        if ($json) {
            $json = str_replace("'", '', $json);
            $json = json_decode($json,true);
        }
        return $json;
    }

    校验日期格式是否正确

    /**
     * 校验日期格式是否正确
     * @author gyj <375023402@qq.com>
     * @createtime 2018-08-27T15:06:51+0800
     * @param      string $date 日期
     * @param      string $formats 需要检验的格式数组
     * @return     boolean
     */
    function checkDateIsValid($date, $formats = array("Y-m-d", "Y/m/d","Ymd")) {
        $unixTime = strtotime($date);
        if (!$unixTime) { //strtotime转换不对,日期格式显然不对。
            return false;
        }
        //校验日期的有效性,只要满足其中一个格式就OK
        foreach ($formats as $format) {
            if (date($format, $unixTime) == $date) {
                return true;
            }
        }
    
        return false;
    }

    记录自定义日志

    /**
    * 记录自定义日志
    * @author gyj  <375023402@qq.com>
    * @createtime 2018-08-24 14:12:01
    * @param $msg 错误信息
    * @param $type 写入类型 wechat aliyun
    * @return [type] [description]
    */
    if(!function_exists('log_result')){
      function log_result($msg='',$type='normal')
      {
        $dir = dirname(LOG_PATH)."/log/".$type."/";
        if(!is_dir($dir)){
            mkdir($dir,0777);
        }
        $dir .= date('Ym')."/";
        $file = $dir.date('d').".log";
        if(!is_dir($dir)){
            mkdir($dir,0777);
        }
        file_put_contents($file,date('Y-m-d H:i:s')."
    ".$msg."
    ---------------------------------------------------------------
    ", FILE_APPEND);
      }
      
    }

    删除文件目录

    /**
    * 删除文件目录
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-11-30 13:34:28
    * @param $dir 文件目录
    * @return 
    */
    if(!function_exists('deldir')){
      function deldir($dir) {
          $dh = opendir($dir);
          while ($file = readdir($dh)) {
              if ($file != "." && $file != "..") {
                  $fullpath = $dir . "/" . $file;
                  if (!is_dir($fullpath)) {
                      unlink($fullpath);
                  } else {
                      deldir($fullpath);
                  }
              }
          }
      }
    }

    获取客户端ip

    /**
    * 获取客户端ip
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-12-16 09:59:54
    * @param 
    * @return string 客户端ip
    */
    if(!function_exists('get_client_ip')){
      function get_client_ip(){
        $cip = "unknown";
        if($_SERVER['REMOTE_ADDR']){
            $cip = $_SERVER['REMOTE_ADDR'];
        }elseif (getenv('REMOTE_ADDR')) {
            $cip = $getenv['REMOTE_ADDR'];
        }
    
          return $cip;
      }
    }

    发送get请求

    /**
     * 发送get请求
     * @author ganyuanjiang  <3164145970@qq.com>
     * @createtime 2017-08-05 14:28:21
     * @param string $url 请求地址
     * @return mixed
     */
    if (!function_exists('https_get')) {
        
      function https_get($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
    
        $res = curl_exec($curl);
        curl_close($curl);
    
        return $res;
      }
    }

    发送post请求

    /**
     * 发送post请求
     * @author ganyuanjiang  <3164145970@qq.com>
     * @createtime 2017-07-26 14:06:04
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
    if (!function_exists('https_request')) {
        
      function https_request($url,$data=null){
        header("Content-type: text/html; charset=utf-8");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
          return curl_error($ch);
        }
    
        curl_close($ch);
        return $tmpInfo;
    
      }
    }

    将时分转换成秒数

    /**
     * 将时分转换成秒数
     * @author gyj <375023402@qq.com>
     * @createtime 2018-08-29T10:15:58+0800
     * @param     
     * @return    秒数
     */
    if (!function_exists('hour_time')) {
    
        function hour_time($unix){
            return strtotime(date('H:i',strtotime($unix)))-strtotime(date('Y-m-d',strtotime($unix)));
        }
    }

    获取毫秒级别的时间戳

    /**
    * 获取毫秒级别的时间戳
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-09-11 10:05:50
    * @param 
    * @return [type] [description]
    */
    if(!function_exists('milli_time')){
      function milli_time()
      {
        //获取毫秒的时间戳
        $time = explode ( " ", microtime () );
        $time = $time[1] . ($time[0] * 1000);
        $time2 = explode( ".", $time );
        $time = $time2[0];
        return $time;
      }
      
    }

    获取一个时间在多少天、小时、分、秒前

    if(!function_exists('time_ago')){
      function time_ago($time){
        $diff = time()-$time;
        if($diff<60){
          return $diff."秒前";
        }else if(60<=$diff && $diff<3600){
          return (int)($diff/60)."分钟前";
        }else if(3600<=$diff && $diff<3600*24){
          return (int)($diff/3600)."小时前";
        }else if((3600*24)<=$diff){
          return (int)($diff/3600/24)."天前";
        }else{
          return "未知";
        }
      }
    }

    encrypt加密解密函数

    /**
    * encrypt加密解密函数
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-07-29 13:54:01
    * @param string string 加密/解密字符串
    * @param operation string E表示加密,D表示解密
    * @param key string 密钥 
    * @return string 加密/解密后字符串
    */
    if(!function_exists('encrypt')){
    
        function encrypt($string,$operation,$key=''){ 
            $key=md5($key); 
            $key_length=strlen($key); 
              $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string; 
            $string_length=strlen($string); 
            $rndkey=$box=array(); 
            $result=''; 
            for($i=0;$i<=255;$i++){ 
                   $rndkey[$i]=ord($key[$i%$key_length]); 
                $box[$i]=$i; 
            } 
            for($j=$i=0;$i<256;$i++){ 
                $j=($j+$box[$i]+$rndkey[$i])%256; 
                $tmp=$box[$i]; 
                $box[$i]=$box[$j]; 
                $box[$j]=$tmp; 
            } 
            for($a=$j=$i=0;$i<$string_length;$i++){ 
                $a=($a+1)%256; 
                $j=($j+$box[$a])%256; 
                $tmp=$box[$a]; 
                $box[$a]=$box[$j]; 
                $box[$j]=$tmp; 
                $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256])); 
            } 
            if($operation=='D'){ 
                if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){ 
                    return substr($result,8); 
                }else{ 
                    return''; 
                } 
            }else{ 
                return str_replace('=','',base64_encode($result)); 
            } 
        }
    }

    AES 加解密算法

    /**
    * AES ECB解密算法
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-09-22 18:01:40
    * @param $data 参数 
    * @param $key 密钥 
    * @return 处理结果
    */
    
    function aes_decode($sStr, $sKey) {
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, hextobin($sKey), base64_decode($sStr), MCRYPT_MODE_ECB);
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s - 1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
    
    function hextobin($hexstr) {
        $n = strlen($hexstr);
        $sbin = "";
        $i = 0;
        while ($i < $n) {
            $a = substr($hexstr, $i, 2);
            $c = pack("H*", $a);
            if ($i == 0) {
                $sbin = $c;
            } else {
                $sbin.=$c;
            }
            $i+=2;
        }
        return $sbin;
    }

     数组排序 根据某个字段排序 

    /**
    * 数组排序 根据某个字段排序 
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-07-30 09:31:48
    * @param $arr  array() 要排序的数组
    * @param $sort  string 排序类型 asc顺序 desc逆序
    * @param $field string 要排序的字段 
    * @return array() 排序过的数组
    */
    if(!function_exists('arr_sort')){
        function arr_sort($arr,$sort,$field){
           $arr_sort = $sort=='asc'?SORT_ASC:SORT_DESC;
           foreach ($arr as $value) {
               $flag[] = $value[$field];
           }
           array_multisort($flag, $arr_sort, $arr); 
           return $arr;
        }
    }

    将对象数组转换成json数组

    /**
    * 将对象数组转换成json数组
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-08-11 14:12:57
    * @param $arr  object 要转换的对象数组
    * @return json array() 转换成json数组
    */
    if(!function_exists('obj_arr')){
        function obj_arr($obj){
           return json_decode(json_encode($obj),true);
        }
    }

    将json_encode一维数组字符串转换成带分割符的字符串

    /**
    * 将json_encode一维数组字符串转换成带分割符的字符串
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-08-31 16:04:13
    * @param $str  string json_encode字符串
    * @param $delimiter  string 分隔符,默认为","
    * @return str string 带分割符的字符串
    */
    if(!function_exists('encode_str')){
        function encode_str($str,$delimiter=","){
           $arr =  json_decode($str,true);
           $new_str = "";
           foreach ($arr as $value) {
               if(!empty($new_str)){
                    $new_str.=",";
               }
               $new_str.=$value;
           }
           return $new_str;
        }
    }

    随机字符串

    /**
    * 随机字符串
    * @author ganyuanjiang  <3164145970@qq.com>
    * @createtime 2017-08-05 14:22:15
    * @param length int 随机字符串长度
    * @return str string 随机字符串
    */
    if(!function_exists('nonce_str')){
      function nonce_str($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
          $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
      }
    }
  • 相关阅读:
    css 解决fixed 布局下不能滚动的问题
    js 正则常用函数 会正则得永生
    巧用call,appl有 根据对象某一属性求最大值
    锚点 , angular 锚点 vue锚点
    css 改变浏览器滚动条的样式
    angular 常用插件集合
    angular4,angular6 父组件异步获取数据传值子组件 undefined 问题
    angular组件之间的通讯
    tomcat的配置详解:[1]tomcat绑定域名
    click 绑定(三)防止事件冒泡
  • 原文地址:https://www.cnblogs.com/jiafeimao-dabai/p/7235645.html
Copyright © 2011-2022 走看看