PHP常用方法集合

PHP / 406人浏览 / 0人评论
/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key 加密密钥
 * @param int $expire 过期时间 单位 秒
 * @return string
 */
function think_encrypt ($data, $key = '', $expire = 0)
{
    $key  = md5 ( empty( $key ) ? config ( 'data_auth_key' ) : $key );
    $data = base64_encode ( $data );
    $x    = 0;
    $len  = strlen ( $data );
    $l    = strlen ( $key );
    $char = '';

    for ( $i = 0; $i < $len; $i++ ) {
        if ( $x == $l ) $x = 0;
        $char .= substr ( $key, $x, 1 );
        $x++;
    }

    $str = sprintf ( '%010d', $expire ? $expire + time () : 0 );

    for ( $i = 0; $i < $len; $i++ ) {
        $str .= chr ( ord ( substr ( $data, $i, 1 ) ) + ( ord ( substr ( $char, $i, 1 ) ) ) % 256 );
    }
    return str_replace ( ['+', '/', '='], ['-', '_', ''], base64_encode ( $str ) );
}

/**
 * 系统解密方法
 * @param string $data 要解密的字符串 (必须是think_encrypt方法加密的字符串)
 * @param string $key 加密密钥
 * @return string
 */
function think_decrypt ($data, $key = '')
{
    $key  = md5 ( empty( $key ) ? config ( 'data_auth_key' ) : $key );
    $data = str_replace ( ['-', '_'], ['+', '/'], $data );
    $mod4 = strlen ( $data ) % 4;
    if ( $mod4 ) {
        $data .= substr ( '====', $mod4 );
    }
    $data   = base64_decode ( $data );
    $expire = substr ( $data, 0, 10 );
    $data   = substr ( $data, 10 );

    if ( $expire > 0 && $expire < time () ) {
        return '';
    }
    $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 ) ) );
        }
    }
    return base64_decode ( $str );
}




/**
 * 生成随机验证码,每一位都是单独从字典中随机获取的字符,字典是0-9纯数字。
 * @param int $length 默认长度6
 * @return string
 */
function create_random_code ($length = 6)
{
    $chars = "0123456789";
    $str   = "";
    for ( $i = 0; $i < $length; $i++ ) {
        $str .= substr ( $chars, mt_rand ( 0, strlen ( $chars ) - 1 ), 1 );
    }
    return $str;
}
/**
 * 校验手机格式
 * @param $phone
 * @return int
 */
function check_mobile ($phone)
{
    return preg_match ( "/1\d{10}$/", $phone );
}


/**
 * [check_email 校验邮箱格式]
 */
function check_email ($email)
{
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    return preg_match ( $pattern, $email );

/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by ($list, $field, $sortby = 'asc')
{
    if ( is_array ( $list ) ) {
        $refer = $resultSet = [];
        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标记字段
 * @return array
 */
function list_to_tree ($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = [];
    if ( is_array ( $list ) ) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ( $list as $key => $data ) {
            $refer[ $data[ $pk ] ] =& $list[ $key ];
        }
        foreach ( $list as $key => $data ) {
            // 判断是否存在parent
            $parentId = $data[ $pid ];
            if ( $root == $parentId ) {
                $tree[] =& $list[ $key ];
            } else {
                if ( isset( $refer[ $parentId ] ) ) {
                    $parent             =& $refer[ $parentId ];
                    $parent[ $child ][] =& $list[ $key ];
                }
            }
        }
    }
    return $tree;
}
/**
 * 压缩文件/目录成zip
 * @param $path
 * @param $zip
 */
function add_file_to_zip ($path, $zip)
{
    $handler = opendir ( $path ); //打开当前文件夹由$path指定。
    while (( $filename = readdir ( $handler ) ) !== false) {
        if ( $filename != "." && $filename != ".." ) {//文件夹文件名字为'.'和‘..’,不要对他们进行操作
            if ( is_dir ( $path . "/" . $filename ) ) {// 如果读取的某个对象是文件夹,则递归
                add_file_to_zip ( $path . "/" . $filename, $zip );
            } else { //将文件加入zip对象
                $pp  = $path . "/" . $filename;
                $pps = explode ( '//', $pp );
                $zip->addFile ( $pp, $pps[ 1 ] );
            }
        }
    }
    @closedir ( $path );
}


/**
 * zip解压
 * @param $filename 要解压的文件
 * @param $path 解压的路径
 * @return bool
 */
function get_zip_originalsize ($filename, $path)
{
    //先判断待解压的文件是否存在
    if ( !file_exists ( $filename ) ) {
        return false;
    }
    //将文件名和路径转成windows系统默认的gb2312编码,否则将会读取不到
    $filename = iconv ( "utf-8", "gb2312", $filename );
    $path     = iconv ( "utf-8", "gb2312", $path );
    //打开压缩包
    $resource = zip_open ( $filename );

    //遍历读取压缩包里面的一个个文件
    while ($dir_resource = zip_read ( $resource )) {
        //如果能打开则继续
        if ( zip_entry_open ( $resource, $dir_resource ) ) {
            //获取当前项目的名称,即压缩包里面当前对应的文件名
            $file_name = $path . zip_entry_name ( $dir_resource );
            $file_name = str_replace ( '/', DS, $file_name );
            //以最后一个“/”分割,再用字符串截取出路径部分
            $file_path = substr ( $file_name, 0, strrpos ( $file_name, DS ) );
            //如果路径不存在,则创建一个目录,true表示可以创建多级目录
            if ( !is_dir ( $file_path ) ) {
                mkdir ( $file_path, 0777, true );
            }
            //如果不是目录,则写入文件
            if ( !is_dir ( $file_name ) ) {
                //读取这个文件
                $file_size = zip_entry_filesize ( $dir_resource );
                //最大读取6M,如果文件过大,跳过解压,继续下一个
                if ( $file_size < ( 1024 * 1024 * 30 ) ) {
                    $file_content = zip_entry_read ( $dir_resource, $file_size );
                    trace ( $file_name );
                    $rr = file_put_contents ( $file_name, $file_content );
                    if ( $rr === false ) {
                        return false; //写入文件失败
                    }
                } else {
                    return false; //文件过大
                }
            }
            //关闭当前
            zip_entry_close ( $dir_resource );
        }
    }
    //关闭压缩包
    zip_close ( $resource );
    return true;
}

/**
 * 清空文件夹及文件夹下的所有文件
 * @param $path "./code/"
 */
function deldir ($path)
{
    //如果是目录则继续
    if ( is_dir ( $path ) ) {
        //扫描一个文件夹内的所有文件夹和文件并返回数组
        $p = scandir ( $path );
        foreach ( $p as $val ) {
            //排除目录中的.和..
            if ( $val != "." && $val != ".." ) {
                //如果是目录则递归子目录,继续操作
                if ( is_dir ( $path . $val ) ) {
                    //子目录中操作删除文件夹和文件
                    deldir ( $path . $val . '/' );
                    //目录清空后删除空文件夹
                    @rmdir ( $path . $val . '/' );
                } else {
                    //如果是文件直接删除
                    @unlink ( $path . $val );
                }
            }
        }
        @rmdir ( $path );
    }
}

/**
 * @param $user_id
 * @return string
 * 创建推荐码
 */
function createcode ($user_id)
{
    static $source_string = 'E5FCDG3HQA4BNPJ2RSTUV67MWX9KYZ';
    $num  = $user_id;
    $code = '';
    while ($num > 0) {
        $mod  = $num % 30;
        $num  = ( $num - $mod ) / 30;
        $code = $source_string[ $mod ] . $code;
    }
    if ( empty( $code[ 3 ] ) )
        $code = str_pad ( $code, 4, '8', STR_PAD_LEFT );
    return $code;
}

/**
 * @param $code
 * @return bool|int
 * 由推荐码获取用户id
 */
function decode ($code)
{
    static $source_string = 'E5FCDG3HQA4BNPJ2RSTUV67MWX9KYZ';
    if ( strrpos ( $code, '8' ) !== false )
        $code = substr ( $code, strrpos ( $code, '8' ) + 1 );
    $len  = strlen ( $code );
    $code = strrev ( $code );
    $num  = 0;
    for ( $i = 0; $i < $len; $i++ ) {
        $num += strpos ( $source_string, $code[ $i ] ) * pow ( 30, $i );
    }
    return $num;
}

/**
 * 输入特殊字符过滤
 * @param $str
 * @return string
 */
function str_filter ($str)
{
    if ( empty ( $str ) || "" == $str ) {
        return "";
    }
    $str = strip_tags ( $str );
    $str = htmlspecialchars ( $str );
    $str = nl2br ( $str );
    return trim ( $str );
}

/**
 * 格式化富文本内容
 * @param $content
 * @return mixed
 */
function format_editor ($content)
{
    $content = htmlspecialchars_decode ( $content );
    //富文本图片路径加上域名
    preg_match_all ( '/<img[^>]*src\s*=\s*([\'"]?)([^\'" >]*)\1/isu', $content, $src );
    foreach ( $src[ 2 ] as $key => $value ) {
        $pos1 = strpos ( $value, 'http://' );
        $pos2 = strpos ( $value, 'https://' );
        if ( $pos1 === false && $pos2 === false ) {
            $host    = config ( 'site_root' );
            $res     = str_replace ( $value, $host . $value, $content );
            $content = $res;
        }
    }

    //图片最大样式设置
    preg_match_all ( '/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', $content, $src1 ); //匹配所以img标签
    foreach ( $src1[ 0 ] as $k => $v ) {
        preg_match_all ( '/<img[^>]*style\s*=\s*([\'"]?)([^\'" >]*)\1/isu', $v, $src );
        if ( count ( $src[ 2 ] ) > 0 ) {
            foreach ( $src[ 2 ] as $key => $value ) {
                $style   = 'style=' . $src[ 1 ][ $key ] . $value . $src[ 1 ][ $key ];
                $style1  = 'style=' . $src[ 1 ][ $key ] . $value . ';max-width:100%;' . $src[ 1 ][ $key ];
                $res     = str_replace ( $style, $style1, $v );
                $content = str_replace ( $v, $res, $content );
            }
        } else {
            $style1  = '<img style="max-width:100%"';
            $res     = str_replace ( '<img', $style1, $v );
            $content = str_replace ( $v, $res, $content );
        }
    }

    $content = str_replace ( '<p>', '<p style="word-break:break-all;">', $content ); //解决长英文单词不换行问题
    return $content;
}
    /**
     *  $time  时间戳
     * return string
     */

    function T ($time)
    {
        $time    = intval ( $time );
        $nowTime = time ();

        $t = $nowTime - $time;// 时间差
        if ( $t <= 10 ) {
            $str = '刚刚';
        } else if ( $t > 10 && $t <= 60 ) {
            $str = $t . '秒内';
        } else if ( $t > 60 && $t <= 60 * 60 ) {
            $str = floor ( $t / 60 ) . '分钟前';
        } else if ( $t > 60 * 60 && $t <= 60 * 60 * 24 ) {
            $str = floor ( $t / ( 60 * 60 ) ) . '小时前';
        } else if ( $t > 60 * 60 * 24 && $t <= 60 * 60 * 24 * 7 ) {
            $str = floor ( $t / ( 60 * 60 * 24 ) ) . '天前';
        } else if ( $t > 60 * 60 * 24 * 7 && $t <= 60 * 60 * 24 * 7 * 4 ) {
            $str = floor ( $t / ( 60 * 60 * 24 * 7 ) ) . '周前';
        } else if ( $t > 60 * 60 * 24 * 7 * 4 && $t <= 60 * 60 * 24 * 365 ) {
            $nowM = date ( 'm', $nowTime );
            $m    = date ( 'm', $time );
            if ( $nowM < $m ) {
                $str = ( 12 - $m ) + $nowM . '个月前';
            } else {
                $str = $nowM - $m . '个月前';
            }
        } else if ( $t > 60 * 60 * 24 * 365 ) {
            $str = date ( 'Y', $nowTime ) - date ( 'Y', $time ) . '年前';
        }

        return $str;
    }

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }

    /**
     * 生成订单号
     */
    function orNum()
    {
        $code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $osn = $code[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $osn;
    }

    /**
     *作用:用于取出二维数组指定元素组
     *$array:[['id'=>1,'name'=>'aaa','age'=>18],['id'=>2,'name'=>'bbb','age'=>24],['id'=>3,'name'=>'ccc','age'=>35]]
     *$index:'id'
     * $value:2
     * return:
     * $type=1:['id'=>2,'name'=>'bbb','age'=>24];
     * $type=2:[['id'=>2,'name'=>'bbb','age'=>24]];
     */
    function filter_by_value ($array, $index, $value,$type=1){
        $newarray = array();
        if(is_array($array) && count($array)>0)
        {
            foreach(array_keys($array) as $key){
                $temp[$key] = $array[$key][$index];
                if ($temp[$key] == $value){
                    if ($type==1){
                        $newarray = $array[$key];
                    }else{
                        $newarray[] = $array[$key];

                    }
                }
            }
        }
        return $newarray;
    }

//搜索和高亮字符串中的关键字

function highlighter_text($text, $words)

{ $split_words = explode( " " , $words ); $color = "red"; foreach($split_words as $word) { $text = preg_replace("|($word)|Ui" , "<span style=\"color:".$color.";\"><b>$1</b></span>" , $text ); } return $text; } $string = "我是一个程序员小白"; $words = "我 小白"; echo highlighter_text($string ,$words);
    /**
     * 通用排序 (上移下移)
     * @param $ids  //排序的数组  11,10,9,25,8(改变后的顺序)
     * @param $changeid  //拖动的记录ID  8
     * @param $field  //操作字段   sort
     * @param $table   //操作的数据表  
     * @param $pk   //主键
     * @param $orderway  //排序的方式
     */
    public function sort($ids,$changeid,$field='sort',$table,$pk='id',$orderway='DESC')
    {
        $sour = $weighdata = [];
        $prikey = $pk ;
        $list = $this->db->query("select {$prikey},{$field} from {$table} where {$prikey} in ({$ids}) order by {$field} {$orderway}")->result_array();
        foreach ($list as $k => $v) {
            $sour[] = $v[$prikey];
            $weighdata[$v[$prikey]] = $v[$field];
        }
        $position = array_search($changeid, explode(',',$ids));  //3
        $desc_id = $sour[$position];
        $sour_id = $changeid;
        $weighids = array();
        $temp = array_values(array_diff_assoc( explode(',',$ids), $sour));//[8,25]
        $sql = "UPDATE {$table} SET {$field}= CASE id ";
        foreach ($temp as $m => $n) {
            if ($n == $sour_id) {
                $offset = $desc_id;
            } else {
                if ($sour_id == $temp[0]) {
                    $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                } else {
                    $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                }
            }
            $weighids[$n] = $weighdata[$offset];
            $sql .= sprintf("WHEN %d THEN %d ", $n, $weighdata[$offset]);
        }
        $up_ids = implode(',', array_keys($weighids));
        $sql .= "END WHERE id IN ($up_ids)";
        $this->db->query($sql);

    }










0 条评论

还没有人发表评论

发表评论 取消回复

记住我的信息,方便下次评论
有人回复时邮件通知我