当前位置:网站首页>编程干货│PHP 常见方法封装

编程干货│PHP 常见方法封装

2022-06-21 21:58:00 极客飞兔

目录

一、curl的get请求

二、curl的post请求

三、随机字符串

四、返回json数据

五、数据过滤

六、重定向

七、获取客户端ip

八、格式化链接

九、隐藏中间字符串

十、是否时间格式

十一、大小格式化

十二、删除文件夹

十三、判断是否整形

十四、金额转中文

十五、检测大陆身份证

十六、计算年龄

十七、获取周几

十八、xml转数组

十九、数组转xml

二十、不区分大小写的in_array实现


一、curl的get请求

function get_curl($url, $timeout = 5) {
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true );
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    $result = curl_exec( $ch );
    curl_close($ch);
    return $result;
}

二、curl的post请求

function post_curl($url, $data, $timeout = 5) {
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true );
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    $result = curl_exec( $ch );
    curl_close($ch);
    return $result;
}

三、随机字符串

function random_str($len=10, $type=1){
    switch($type){
        case 2:
            $chars='0123456789';
            break;
        case 3:
            $chars='abcdefghijklmnopqrstuvwxyz';
            break;
        case 4:
            $chars='ABDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        case 5:
            $chars='abcdefghijklmnopqrstuvwxyzABDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        case 6:
            $chars='abcdefghijklmnopqrstuvwxyz0123456789';
            break;
        default:
            $chars='abcdefghijklmnopqrstuvwxyzABDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            break;
    }

    $str = '';
    for ( $i = 0; $i <$len; $i++ ){
        $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $str;
}

四、返回json数据

function json_back($data, $is_exit = true) {
    $callback = $_GET['callback'] ?? '';
    if ($callback) {
        echo '' . $callback . "(" . json_encode($data, JSON_UNESCAPED_UNICODE) . ")";
    } else {
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    if ($is_exit) exit();
}

五、数据过滤

function check_data($data){
    if(is_array($data)){
        foreach($data as $key => $v){
            $data[$key] = $this->check_data($v);
        }
    }else{
        $data = trim($data);
        $data = strip_tags($data);
        $data = htmlspecialchars($data);
        $data = addslashes($data);
    }
    return $data;
}

六、重定向

function redirect($url = 'https://blog.csdn.net/weixin_41635750'){
    if (!headers_sent()) {
        header("Location: {$url}");
        exit();
    }else{
        $str = "<meta http-equiv='Refresh' content='0;URL={$url}'>";
        exit($str);
    }
}

七、获取客户端ip

function get_real_ip() {
    if(@$_SERVER["HTTP_ALI_CDN_REAL_IP"]){
        $ip = $_SERVER["HTTP_ALI_CDN_REAL_IP"];
    }
    elseif (@$_SERVER["HTTP_X_FORWARDED_FOR"] ?: false) {
        $ip  = $_SERVER["HTTP_X_FORWARDED_FOR"];
        $ips = explode(',', $ip);
        $ip  = $ips[0];
    } elseif (@$_SERVER["HTTP_CDN_SRC_IP"] ?: false) {
        $ip = $_SERVER["HTTP_CDN_SRC_IP"];
    } elseif (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED')) {
        $ip = getenv('HTTP_X_FORWARDED');
    } elseif (getenv('HTTP_FORWARDED_FOR')) {
        $ip = getenv('HTTP_FORWARDED_FOR');
    } elseif (getenv('HTTP_FORWARDED')) {
        $ip = getenv('HTTP_FORWARDED');
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $ip = str_replace(array('::ffff:', '[', ']'), array('', '', ''), $ip);

    return $ip;
}

八、格式化链接

function formatLink($url, array $param = []) {
        if (!empty($param)) {
            $suffix = http_build_query($param);
            $url = strpos($url, '?') > 0 ? $url . '&' . $suffix : $url . '?' . $suffix;
        }

        return $url;
    }

九、隐藏中间字符串

function hiddenPartStr($str) {
        $strLen = mb_strlen($str);
        if ($strLen > 1 && $strLen <= 3) $str = mb_substr($str, 0, 1) . str_repeat('*', $strLen - 1);
        if ($strLen > 3) {
            $halfPosition = (int)($strLen / 2);
            $startPosition = (int)($halfPosition / 2);
            $diffPosition = $halfPosition - $startPosition;
            $endPosition = $strLen % 2 == 0 ? $halfPosition + $diffPosition : (++$halfPosition) + $diffPosition;
            $str = mb_substr($str, 0, $startPosition) . str_repeat('*', $endPosition - $startPosition) . mb_substr($str, $endPosition, $strLen - $endPosition);
        }

        return $str;
    }

十、是否时间格式

function isDatetime($datetime) {
    $isTime = strtotime($datetime);
    return $isTime !== FALSE && $isTime != -1;
}

十一、大小格式化

function toSize($bytes, $precision = 2) {
        $rank = 0;
        $size = $bytes;
        $unit = "B";
        while ($size > 1024) {
            $size = $size / 1024;
            $rank++;
        }

        $size = round($size, $precision);
        switch ($rank) {
            case "1":
                $unit = "KB";
                break;
            case "2":
                $unit = "MB";
                break;
            case "3":
                $unit = "GB";
                break;
            case "4":
                $unit = "TB";
                break;
        }
        return $size . "" . $unit;
    }

十二、删除文件夹

function deleteDir($dirname) {
        if (!file_exists($dirname)) return false;
        array_map('unlink', glob("{$dirname}/*"));
        @rmdir($dirname);
        return true;
    }

十三、判断是否整形

function isInt($str) {
        if (is_string($str)) {
            return ctype_digit($str);
        } else {
            return is_int($str);
        }
    }

十四、金额转中文

function moneyToString($num) {
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        //精确到分后面就不要了,所以只留两个小数位
        $num = round($num, 2);

        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大,请检查";
        }

        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }
            //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;

            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            //结束循环
            if ($num == 0) {
                break;
            }
        }
        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }

        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }

        //将处理的汉字加上“整”
        if (empty($c)) {
            return "零元整";
        } else {
            return $c . "整";
        }
    }

十五、检测大陆身份证

function verifyIdCard($idCard) {
        if (!is_numeric(substr($idCard, 0, 3))) return true;
        $set = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        $ver = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'];
        $arr = str_split($idCard);
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            if (!is_numeric($arr[$i])) {
                return false;
            }
            $sum += $arr[$i] * $set[$i];
        }
        $mod = $sum % 11;
        if (strcasecmp($ver[$mod], $arr[17]) != 0) {
            return false;
        }
        return true;
    }

十六、计算年龄

function getAge($birthDate) {
        $age = strtotime($birthDate);
        if ($age === false) return 0;
        list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
        $now = strtotime("now");
        list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
        $age = $y2 - $y1;
        if ((int)($m2 . $d2) < (int)($m1 . $d1))
            $age -= 1;
        return $age;
    }

十七、获取周几

function getWeekCN($timestamp = 0) {
        $week = ['日', '一', '二', '三', '四', '五', '六'];

        if ($timestamp == 0) $timestamp = time();
        
        return $week[date("w", $timestamp)];
    }

十八、xml转数组

function xmlToArray($xml) {
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

十九、数组转xml

function arrayToXml($arr) {
        $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;
    }

二十、不区分大小写的in_array实现

function inArrayCase($value, $array) {
    return in_array(strtolower($value), array_map('strtolower', $array));
}
原网站

版权声明
本文为[极客飞兔]所创,转载请带上原文链接,感谢
https://autofelix.blog.csdn.net/article/details/117176817

随机推荐