美文网首页
php常用杂项

php常用杂项

作者: 胡乱唱歌ing | 来源:发表于2018-12-10 15:18 被阅读0次

    1.对_GET,_POST 参数进行转义

    /**
     * 递归方式的对变量中的特殊字符进行转义
     */
    function addslashes_deep($value)
    {
        if(empty($value))
        {
             return $value;
        }
        else
        {
            return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
        }
    }
    
    /* 对用户传入的变量进行转义操作。*/
    if (!get_magic_quotes_gpc())
    {
        if (!empty($_GET))
        {
            $_GET  = addslashes_deep($_GET);
        }
        if (!empty($_POST))
        {
            $_POST = addslashes_deep($_POST);
        }
    
        $_COOKIE   = addslashes_deep($_COOKIE);
        $_REQUEST  = addslashes_deep($_REQUEST);
    }
    

    2.获取文件后缀名,并判断是否合法

    /**
     * 获取文件后缀名,并判断是否合法
     *
     * @param string $file_name
     * @param array $allow_type
     * @return blob
     */
    function get_file_suffix($file_name, $allow_type = array())
    {
        //$file_suffix = strtolower(array_pop(explode('.', $file_name)));
        $file_suffix = strtolower(strrchr($file_name,'.'));
       
        if (empty($allow_type))
        {
            return $file_suffix;
        }
        else
        {
            if (in_array($file_suffix, $allow_type))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    var_dump(get_file_suffix(('a.txt'),array('.gif','.bmp')));
    

    3.验证输入的邮件地址是否合法

    /**
     * 验证输入的邮件地址是否合法
     *
     * @access  public
     * @param   string      $email      需要验证的邮件地址
     *
     * @return bool
     */
    function is_email($user_email)
    {
        $chars = "/^[a-z0-9]+@[a-z0-9]+\.[a-z0-9]+$/i";
        if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
        {
            if (preg_match($chars, $user_email))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    var_dump(is_email('123@qq.cerom'));
    

    4.电话号码替换*

    /***
    phone replace 13049638170  13049****70;
    */
    function replacephone($phone)
    { 
         $patt="/(1[0-9]{2})[0-9]{5}([0-9]{3})/";
         $replace = "$1****$2";
         $phone = preg_replace($patt,$replace, $phone);
         echo $phone;
    }
    或
    echo substr_replace($phone,'****',3,4);
    

    5.无限分级

    /**无限级分类***/
    $area = array(
        0=>array('cat_id'=>1,'cat_name'=>'北京市','parent_id'=>0),
        1=>array('cat_id'=>2,'cat_name'=>'馆陶县','parent_id'=>5),
        2=>array('cat_id'=>3,'cat_name'=>'海淀区','parent_id'=>1),
        3=>array('cat_id'=>4,'cat_name'=>'朝阳区','parent_id'=>1),
        4=>array('cat_id'=>5,'cat_name'=>'邯郸市','parent_id'=>6),
        5=>array('cat_id'=>6,'cat_name'=>'河北省','parent_id'=>0),
    );
    //由父辈向下找子孙
    function catsort($arr,$parent_id = 0,$len = 0)
    { 
    
        static $res = array(); 
        foreach ($arr as $key => $val) {
            if($val['parent_id'] == $parent_id)
            { 
    
                $val['len'] = $len + 1;
                $res[] = $val;
                catsort($arr,$val['cat_id'],$val['len']);
            }
    
        }
        return $res;
    }
    //由父辈向下找子孙
    function catsort2($arr,$parent_id = 0,$len = 0)
    { 
    
        $res = array(); 
        foreach ($arr as $key => $val) {
            if($val['upid'] == $parent_id)
            { 
                $val['children'] = catsort2($arr,$val['id']);
                $res[] = $val;
            }
        }
        return $res;
    }
    
    //由子孙像父辈找
    function tree($arr,$cat_id = 4)
    { 
        static $tree = array();
        foreach ($arr as $key => $val) {
            if($val['cat_id'] == $cat_id)
            { 
                $tree[] = $val;
                tree($arr,$val['parent_id']);
            }
        }
        return $tree;
    }
    

    6.php下载远程图片

    function dlPicuter($url,$path) {
        if(!is_dir($path))
        { 
            mkdir($path,0755,true);
        }
        if(preg_match('/https:\/\/.*?\.png/is',$url))
        {
            $save_filename = date('YmdHis').'.jpg';
            try{
                $content = @file_get_contents($url);
                if($content != "")
                {
                    file_put_contents($path.$save_filename,$content);
                    return $path.$save_filename;
                }
                else {
                    return '';
                }
            }catch(Exception $e)
            { 
            }
        }
     }
    echo  dlPicuter('https://www.baidu.com/img/bdlogo.png','./pp/');
    

    7.gbk-uft8转码

     ///php UFT-8 ---> GBK;
     $html = mb_convert_encoding($html, 'GBK', 'UTF-8');
    ///gbk -->utf-8
     iconv("GBK","UTF-8",$html);
    

    8.中文如乱码截取

    function jiequ($str,$len="24")
    { 
        return mb_substr($str,0,$len,"UTF-8");
    }
    

    9.过滤非法参数

    //过滤非法的参数
    function parts(array $array, array $keys)
    {
        foreach (array_keys($array) as $key) {
            if (!in_array($key, $keys)) {
                unset($array[$key]);
            }
        }
    
        return $array;
    }
    
    //parts($_POST,['id','name','password','insertime']);
    

    10.判断是否缺少必要的参数

    //判断是否缺少必要的参数
    function requireds(array $array, array $keys, $strictMode = false)
    {
        foreach ($keys as $key) {
            if (!array_key_exists($key, $array)) {
                return false;
            }
            if ($strictMode && (is_null($array[$key]) || $array[$key] === "" || $array[$key] === 0)) {
                return false;
            }
        }
    
        return true;
    }
    

    11.curl 的POST与GET

    /** 
    * Send a POST requst using cURL 
    * @param string $url to request 
    * @param array $post values to send 
    * @param array $options for cURL 
    * @return string 
    */ 
    function curl_post($url, array $post = NULL, array $options = array()) 
    { 
        $defaults = array( 
            CURLOPT_POST => 1, 
            CURLOPT_HEADER => 0, 
            CURLOPT_URL => $url, 
            CURLOPT_FRESH_CONNECT => 1, 
            CURLOPT_RETURNTRANSFER => 1, 
            CURLOPT_FORBID_REUSE => 1, 
            CURLOPT_TIMEOUT => 4, 
            CURLOPT_POSTFIELDS => http_build_query($post) 
        ); 
    
        $ch = curl_init(); 
        curl_setopt_array($ch, ($options + $defaults)); 
        if( ! $result = curl_exec($ch)) 
        { 
            trigger_error(curl_error($ch)); 
        } 
        curl_close($ch); 
        return $result; 
    } 
    
    /** 
    * Send a GET requst using cURL 
    * @param string $url to request 
    * @param array $get values to send 
    * @param array $options for cURL 
    * @return string 
    */ 
    function curl_get($url, array $get = NULL, array $options = array()) 
    {    
        $defaults = array( 
            CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get), 
            CURLOPT_HEADER => 0, 
            CURLOPT_RETURNTRANSFER => TRUE, 
            CURLOPT_TIMEOUT => 4 
        ); 
        
        $ch = curl_init(); 
        curl_setopt_array($ch, ($options + $defaults)); 
        if( ! $result = curl_exec($ch)) 
        { 
            trigger_error(curl_error($ch)); 
        } 
        curl_close($ch); 
        return $result; 
    } 
    

    12.openssl对文件/字符串加密解密

    class Mycrypt{ 
        private $passwd = ''; //字符串长度必须是13位
        private $sign = ''; //字符长度必须是16位
        public function __construct($passwd = 'sjhfjewQ!dlfg',$sign = 'JAqwo12U!@askdas')
        { 
            $this->passwd = $passwd;
            $this->sign = $sign;
        }
        private function sslPrm()
        {
            return array($this->passwd,$this->sign,"aes-256-cbc");
        }
        public function sslEnc($msg)
        {
            list ($pass, $iv, $method)= $this->sslPrm();
            if(function_exists('openssl_encrypt'))
            {
                return urlencode(openssl_encrypt(urlencode($msg), $method, $pass, false, $iv));
            }
            else
            {
                return urlencode(exec("echo \"".urlencode($msg)."\" | openssl enc -".urlencode($method)." -base64 -nosalt -K ".bin2hex($pass)." -iv ".bin2hex($iv)));
            }
        }
        public  function sslDec($msg)
        {
            list ($pass, $iv, $method) = $this->sslPrm();
            if(function_exists('openssl_decrypt'))
            {
                return trim(urldecode(openssl_decrypt(urldecode($msg), $method, $pass, false, $iv)));
            }
            else
            {
                return trim(urldecode(exec("echo \"".urldecode($msg)."\" | openssl enc -".$method." -d -base64 -nosalt -K ".bin2hex($pass)." -iv ".bin2hex($iv))));
            }
        }
    
    }
    

    13.加密解密

    function encryptDecrypt($string, $key="password", $decrypt="DECODE"){ 
        if($decrypt){ 
            $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12"); 
            return $decrypted; 
        }else{ 
            $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key)))); 
            return $encrypted; 
        } 
    }
    
    1. 导出CSV
    public function exportToCsv($fileName = '', $headArr = [], $data = [])
        {
            
            @ob_end_clean();  //清除内存
            ob_start();
            @header("Content-Type: text/csv");
            @header("Content-Disposition:filename=".$fileName.'.csv');
            $fp=fopen('php://output','w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp,$headArr);
            $index = 0;
            foreach ($data as $item) {
                if($index==1000){ //每次写入1000条数据清除内存
                    $index=0;
                    ob_flush();//清除内存
                    flush();
                }
                $index++;
                fputcsv($fp,$item);
            }
     
            @ob_flush();
            flush();
            ob_end_clean();
            return;
        }
    

    相关文章

      网友评论

          本文标题:php常用杂项

          本文链接:https://www.haomeiwen.com/subject/ukgrhqtx.html