zoukankan      html  css  js  c++  java
  • php常用函数归纳

    php常用函数归纳:

    /**
     * 截取指定长度的字符
     * @param type $string  内容
     * @param type $start 开始
     * @param type $length 长度
     * @return type
     */
    function ds_substing($string, $start=0,$length=80) {
        $string = strip_tags($string);
        $string = preg_replace('/s/', '', $string);
        return mb_substr($string, $start, $length);
    }
    /**
     * 获取当前域名及根路径
     * @return string
     */
    function base_url()
    {
        $request = Request::instance();
        $subDir = str_replace('\', '/', dirname($request->server('PHP_SELF')));
        return $request->scheme() . '://' . $request->host() . $subDir . ($subDir === '/' ? '' : '/');
    }
    /**
     * 写入日志   
     * @param string|array $values  
     * @param string $dir
     * @return bool|int
     */
    function write_log($values, $dir)
    {
        if (is_array($values))
            $values = print_r($values, true);
        // 日志内容
        $content = '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $values . PHP_EOL . PHP_EOL;
        try {
            // 文件路径
            $filePath = $dir . '/logs/';
            // 路径不存在则创建
            !is_dir($filePath) && mkdir($filePath, 0755, true);
            // 写入文件
            return file_put_contents($filePath . date('Ymd') . '.log', $content, FILE_APPEND);
        } catch (Exception $e) {
            return false;
        }
    }
    /**
     * curl请求指定url (get)
     * @param $url
     * @param array $data
     * @return mixed
     */
    function curl($url, $data = [])
    {
        // 处理get数据
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
    
    /**
     * curl请求指定url (post)  
     * @param $url
     * @param array $data
     * @return mixed
     */
    function curlPost($url, $data = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    /**
     * 多维数组合并
     * @param $array1
     * @param $array2
     * @return array
     */
    function array_merge_multiple($array1, $array2)
    {
        $merge = $array1 + $array2;
        $data = [];
        foreach ($merge as $key => $val) {
            if (
                isset($array1[$key])
                && is_array($array1[$key])
                && isset($array2[$key])
                && is_array($array2[$key])
            ) {
                $data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
            } else {
                $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
            }
        }
        return $data;
    }
    /**
     * 二维数组排序
     * @param $arr
     * @param $keys
     * @param bool $desc
     * @return mixed
     */
    function array_sort($arr, $keys, $desc = false)
    {
        $key_value = $new_array = array();
        foreach ($arr as $k => $v) {
            $key_value[$k] = $v[$keys];
        }
        if ($desc) {
            arsort($key_value);
        } else {
            asort($key_value);
        }
        reset($key_value);
        foreach ($key_value as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }
    /**
     * 数据导出到excel(csv文件)
     * @param $fileName
     * @param array $tileArray
     * @param array $dataArray
     */
    function export_excel($fileName, $tileArray = [], $dataArray = [])
    {
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $fileName);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($dataArray as $item) {
            if ($index == 1000) {
                $index = 0;
                ob_flush();
                flush();
            }
            $index++;
            fputcsv($fp, $item);
        }
        ob_flush();
        flush();
        ob_end_clean();
    }
    //生成XML
    function makeXML($data_array){
        $content='<?xml version="1.0" encoding="utf-8"?><urlset>';
        foreach($data_array as $data){
            $content.= create_item($data);
        }
        $content.='</urlset>';
        $fp=fopen('sitemap.xml','w+');
        fwrite($fp,$content);
        fclose($fp);
    }
        /**
         * 加密字符串
         * @param string $str 字符串
         * @param string $key 加密key
         * @param integer $expire 有效期(秒)     
         * @return string
         * ord() 函数返回字符串的首个字符的 ASCII 值。
         */
        public static function encrypt($data,$key,$expire=0) {
            $expire = sprintf('%010d', $expire ? $expire + time():0);
            $key    =   md5($key);
            $data   =   base64_encode($expire.$data);
            $char = "";
            $str = "";
            $x=0;
            $len = strlen($data);
            $l = strlen($key);
            for ($i=0;$i< $len;$i++) {
                if ($x== $l) $x=0;
                $char   .=substr($key,$x,1);
                $x++;
            }
    
            for ($i=0;$i< $len;$i++) {
                $str    .=chr(ord(substr($data,$i,1))+(ord(substr($char,$i,1)))%256);
            }
            return $str;
        }
    
        /**
         * 解密字符串
         * @param string $str 字符串
         * @param string $key 加密key
         * @return string
         */
        public static function decrypt($data,$key) {
            $key    =   md5($key);
            $x=0;
            $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)));
                }
            }
            $data = base64_decode($str);
            $expire = substr($data,0,10);
            if($expire > 0 && $expire < time()) {
                return '';
            }
            $data   = substr($data,10);
            return $data;
        }
    //模拟ip
        function get_rand_ip()
        {
          $arr_1 = array("218","218","66","66","218","218","60","60","202","204","66","66","66","59","61","60","222","221","66","59","60","60","66","218","218","62","63","64","66","66","122","211");
          $randarr= mt_rand(0,count($arr_1)-1);
          $ip1id = $arr_1[$randarr];
          $ip2id=  round(rand(600000,  2550000)  /  10000);
          $ip3id=  round(rand(600000,  2550000)  /  10000);
          $ip4id=  round(rand(600000,  2550000)  /  10000);
          return  $ip1id . "." . $ip2id . "." . $ip3id . "." . $ip4id;
        }
    //爬虫函数
        function curl_get($url)
        {
            $ch = curl_init(); 
            if(strpos($url,'https')!==false)
            {
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            }
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5' );//模拟浏览器
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:'.get_rand_ip())); //构造IP 
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT,30);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);//curl 抓取结果不直接输出
            $out = curl_exec($ch);
            curl_close($ch);
            return $out;
    
        }
        //过滤标签
        function content_format($content){
            $content = str_replace("'",'‘',$content);    
            $content = preg_replace('/</?p[^>]*>/i','<br>',$content);
            $content = preg_replace('/<br[s/br><&nbsp;]*>(s*|&nbsp;)*/i','<br><br>&nbsp;&nbsp;&nbsp;&nbsp;',$content);
    
    
            if (stripos($content,'<table')) {
                
                $content = preg_replace('/(<br>|&nbsp;|s)*(<table[^>]*)>/iU','$2 align=center>',$content);
                $content = preg_replace('/</table>(<br>|s)*/i','</table>',$content);
                $content = str_replace('tdclass','td class',$content);
                $content = str_replace('<table','<table ',$content);
                $content = str_replace('<tdcolspan','<td colspan ',$content);
                $content = preg_replace('/[/center](s|<br>)*/','[/center]',$content);
                $content = preg_replace('/</table>(&nbsp;|s)*([x80-xff]*)/','</table>&nbsp;&nbsp;&nbsp;&nbsp;$2',$content);
                $content = preg_replace('/</table>(&nbsp;|s|<br>)*(</?td|</?tr|</?table)/i','</table>$2',$content);        
            }
            $content = preg_replace('/[center](<br>|s|&nbsp;)*[/center]/','',$content);
            
            
            if (stripos($content,'<style') !== false) {
                $content = preg_replace('/(s|&nbsp;|<br[s/br><&nbsp;]*>)*(<style.*</style>)(s|&nbsp;|<br[s/br><&nbsp;]*>)*/isU','$2',$content);
            }
            $content = preg_replace('/(&nbsp;){4,}s*/','&nbsp;&nbsp;&nbsp;&nbsp;',$content);
            
            $content = preg_replace('/</?br[^>]*>/iU','<br>', $content);
            return $content;
        }
        //创建多层目录
        function mk_dir($dir)
        {
            if ('/' == DIRECTORY_SEPARATOR) {
                $dir = str_replace('\', DIRECTORY_SEPARATOR, $dir);
            } else {
                $dir = str_replace('/', DIRECTORY_SEPARATOR, $dir);
            }
            if (substr($dir, -1) != DIRECTORY_SEPARATOR) {
                $dir = dirname($dir);
            }
            if (file_exists($dir)) {
                return true;
            }
            $dirs = explode(DIRECTORY_SEPARATOR, $dir);
            if (count($dirs)) {
                foreach ($dirs as $dir) {
                    $tdir .= $dir . DIRECTORY_SEPARATOR;
                    if ($tdir == DIRECTORY_SEPARATOR || preg_match('/^[a-z]:(|/)$/i',$tdir)) {
                        continue;
                    }
                    if (!file_exists($tdir)) {
                        if (!@mkdir($tdir, 0777)) {
                            return false;
                        }
                    }
                }
            }
        }
        //文件扩展名
        function getFileExt($filePath)
        {
            return(trim(strtolower(substr(strrchr($filePath, '.'), 1))));
        }
        //压缩图片
        function image_png_size_add($imgsrc,$imgdst,$newwith=960,$newheight=960){ 
          //判断文件大小是否超过既定值,没有直接返回false
          if(!check_filesize($imgsrc,'200')) return false;
          list($width,$height,$type)=getimagesize($imgsrc); 
          $scale = $width/$newwith;
          $new_width = ($scale>1?$width/$scale:$width); 
          $new_height =($scale>1?$height/$scale:$height); 
          switch($type){ 
            case 1: 
              $giftype=check_gifcartoon($imgsrc); 
              if($giftype){ 
                $image_wp=imagecreatetruecolor($new_width, $new_height); 
                $image = imagecreatefromgif($imgsrc); 
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
                imagejpeg($image_wp, $imgdst,75); 
                imagedestroy($image_wp); 
                return true;
              } 
              break; 
            case 2: 
              $image_wp=imagecreatetruecolor($new_width, $new_height); 
              $image = imagecreatefromjpeg($imgsrc); 
              imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
              imagejpeg($image_wp, $imgdst,75); 
              imagedestroy($image_wp); 
              return true;
              break; 
            case 3:  
              $image_wp=imagecreatetruecolor($new_width, $new_height); 
              $image = imagecreatefrompng($imgsrc); 
              imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
              imagejpeg($image_wp, $imgdst,75); 
              imagedestroy($image_wp);
              return true;      
              break; 
          } 
        }
        //desription 判断是否文件大小是否超过既定值
        function check_filesize($url,$size='200'){ 
            $filemsg = get_headers($url,true);
            $filesize = intval($filemsg["Content-Length"]/1024);
            if($filesize>$size) return true;
            else return false;
        }
  • 相关阅读:
    windows系统下hosts文件的改写(为了测试nginx内网的证书代理,需要做域名解析)
    搭建jenkins
    Jsp传递参数的方法
    防止自己的网站被别人frame引用造成钓鱼
    Jsp连接Mysql数据库取数方法
    Win7下安装Mysql方法
    jsp建立错误页自动跳转
    jsp-forward跳转
    jvm栈和堆详解
    Gridpanel多种操作帮助文档
  • 原文地址:https://www.cnblogs.com/jackzhuo/p/11883702.html
Copyright © 2011-2022 走看看