美文网首页
php 自定义公共函数 2023-02-07

php 自定义公共函数 2023-02-07

作者: 阿然学编程 | 来源:发表于2023-02-07 14:04 被阅读0次
    • curl请求函数
    /**
     * @param $url
     * @param string $params
     * @param int $ispost
     * @param array $header
     * @return bool|string
     */
    function http_curl($url, $params = '', $ispost = 0, $header = array())
    {
        $options = array(
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
        );
    
        $params = is_array($params) ? http_build_query($params) : $params;
    
        $ch = curl_init();
    
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if (!empty($params)) {
                $url .= '?' . $params;
            }
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        } elseif ($ispost && !empty($params)) {
            // 设置 Content-Type 和 Content-Length
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
                'Content-Length:' . strlen($params)
            ));
        }
        curl_setopt_array($ch, $options);
    
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        curl_close($ch);
    
        return $response;
    }
    
    • 检查请求数据是否为 JSON 格式并将其解码为数组
    function is_json()
    {
        // 验证 Content-Type
        if (strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== 0) {
            return false;
        }
    
        try {
            $dataJson = file_get_contents('php://input');
            $dataArr = json_decode($dataJson, true);
    
            if (json_last_error() !== JSON_ERROR_NONE || !is_array($dataArr)) {
                return false;
            }
    
            return $dataArr;
        } catch (Exception $e) {
            return false;
        }
    }
    
    • 接受 POST 和 GET 参数
    /**
     * 接受 POST 和 GET 参数
     *
     * @param string $name
     * @param null $default
     * @return array|mixed|null
     */
    function get_input($name = '', $default = null)
    {
        $data = isset($_POST[$name]) ? trim(strip_tags($_POST[$name])) : (isset($_GET[$name]) ? trim(strip_tags($_GET[$name])) : $default);
    
        return $name ? $data : array_merge($_GET, $_POST);
    }
    
    • php 使用FTP下载文件到本地
    /**
     * @param array $ftpConfig FTP配置
     * @param $localDir 本地保存路径例如:'E:/phpstudy_pro/WWW/beifen_test/test' 后面没有 /
     * @param string $remoteDir 服务器ftp路径默认:'.' 或者 '/'
     * @param bool $mode
     */
    function download_ftp_File(array $ftpConfig, $localDir, $remoteDir = '.', $mode = true)
    {
        if (!file_exists($localDir)) {
            mkdir($localDir, 0777, true);
        }
    
        $ftp = ftp_connect($ftpConfig['server'], $ftpConfig['port']);
        if (!$ftp) {
            echo '连接 FTP 服务器失败!';
            exit();
        }
    
        if (!ftp_login($ftp, $ftpConfig['username'], $ftpConfig['password'])) {
            echo '登录 FTP 服务器失败!';
            ftp_close($ftp);
            exit();
        }
    
        ftp_pasv($ftp, $mode); // 默认:被动模式 true , 主动模式:false
    
        $fileList = ftp_nlist($ftp, $remoteDir);
        if ($fileList === false) {
            echo '无法获取远程文件列表' . "\n";
            ftp_close($ftp);
            exit();
        }
    
        foreach ($fileList as $file) {
            $filename = basename($file);
            if ($filename === '.' || $filename === '..') {
                continue;
            }
    
            $localFile = $localDir . '/' . $filename;
    
            if (ftp_size($ftp, $file) == -1) { // 目录
                if (!file_exists($localFile)) {
                    mkdir($localFile);
                }
                download_ftp_File($ftpConfig, $localFile, $file . '/', $mode);
            } else { // 文件
                if (ftp_get($ftp, $localFile, $file, FTP_BINARY)) {
                    $msg = ($mode ? '(被动模式)' : '(主动模式)') . '-下载文件:' . $localFile . PHP_EOL;
                    echo $msg;
                } else {
                    $msg = ($mode ? '(被动模式)' : '(主动模式)') . '-下载文件失败:' . $localFile . PHP_EOL;
                    echo $msg;
                }
            }
        }
        //关闭连接
        ftp_close($ftp);
    }
    
    //使用示例
    $ftp = [
        'server' => 'serverip',
        'port' => 21,
        'username' => '用户名',
        'password' => '密码',
    ];
    $remoteDir = '/';
    $localDir = 'E:/phpstudy_pro/WWW/beifen_test/test';
    
    download_ftp_File($ftp, $localDir, $remoteDir, false);
    
    • 生成随机整数
    /**
     * 生成随机整数
     * @param $min
     * @param $max
     * @param $length
     * @return array
     */
    function rand_arr_Int($min, $max, $length)
    {
        $randomInts = [];
        $length = min($max - $min + 1, $length); // 长度不能超过可选数的数量
        while (count($randomInts) < $length) {
            $rand = mt_rand($min, $max);
            if (!in_array($rand, $randomInts, true)) {
                $randomInts[] = $rand;
            }
        }
        return $randomInts;
    }
    
    • 生成保留后俩位的随机小数
        /**
         * @param $min
         * @param $max
         * @return string
         * 生成保留后俩位的随机小数
         */
        function rand_float($min, $max)
        {
            mt_srand(hexdec(substr(uniqid(), -8)) ^ time()); // 生成随机数种子(如果可以接受重复这段代码可注释)
            $randomNumber = mt_rand($min * 100, $max * 100) / 100; // 生成范围在 $min ~ $max 之间的浮点数
            return number_format($randomNumber, 2, '.', ''); // 格式化为保留两位小数的字符串并返回
        }
    
    • 自定义密码加密
    /**
     * 自定义密码加密
     * @param $password
     * @return string
     */
    function password_md5_encrypt($password)
    {
        return md5(sha1(md5($password)));
    }
    
    • hash 密码加密
    /**
     * 密码加密生成哈希值
     * @param $password 待哈希的密码
     * @param int $algorithm 哈希算法,当前支持的算法:1:PASSWORD_DEFAULT 2:PASSWORD_BCRYPT ,默认使用 2:PASSWORD_BCRYPT
     * @param array $options 哈希选项,默认为空
     * @return bool|string 返回密码哈希值,失败时返回 false
     */
    function set_hash_password($password, $algorithm = PASSWORD_BCRYPT, $options = array())
    {
        $hash = password_hash($password, $algorithm, $options);
        if ($hash === false) {
            // 哈希生成失败
            return false;
        }
        return $hash;
    }
    
    • 手机号验证
    /**
     * 手机号验证
     * @param $phone
     * @return bool
     */
    function is_mobile($phone)
    {
        $chars = "/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/";
        if (!preg_match($chars, $phone)) {
            return false;
        }
        return true;
    }
    
    • curl get || post请求
    /**
     * curl - get请求
     * @param $url
     * @return bool|string
     */
    
    function http_get($url)
    {
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }
    
    
    /**
     * curl - post请求
     * @param $url
     * @param $post_data
     * @param string $header
     * @return bool|string
     */
    
    function http_post($url, $post_data, $header = '')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 设置请求方式为post
        curl_setopt($ch, CURLOPT_POST, true);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        // 请求头,可以传数组
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HEADER, $header);
        }
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    
    • 验证https
        /**
         * 是否https
         */
    function is_HTTPS()
    {
        if (!isset($_SERVER['HTTPS'])) {
            return false;
        }
        if ($_SERVER['HTTPS'] === 1) { //Apache
            return true;
        } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
            return true;
        } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
            return true;
        }
        return false;
    }
    
    • 验证日期
    /**
     * 是否为日期格式
     * @param $timevalue
     * @return bool|false|string
     */
    function isDateTime($timevalue)
    {
        if (!empty($timevalue)) {
            if (is_numeric($timevalue)) {
                //如果转换出的时间有误差,请同步服务器时间
                return gmdate('Y-m-d H:m:s', intval(($timevalue - 25569) * 3600 * 24));
            } else {
                $ret = strtotime($timevalue);
                if ($ret !== FALSE && $ret != -1) {
                    return $timevalue;
                }
                return false;
            }
        }
        return false;
    }
    
    • 转码
    //gbk 2 utf8
    function gbk2utf8($data = '')
    {
        if (is_array($data)) {
            return array_map('gbk2utf8', $data);
        }
        return iconv('gbk', 'utf-8', $data);
    }
    
    //utf8 2 gbk
    function utf82gbk($data = '')
    {
        if (is_array($data)) {
            return array_map('gbk2utf8', $data);
        }
        return iconv('utf-8', 'gbk', $data);
    }
    
    • 导出csv
    /**
     * 导出CSV
     * @param $filename
     * @param array $titleArray
     * @param array $dataArray
     */
    function pull_csv($filename, array $titleArray, array $dataArray)
    {
    
        // 设置最大执行时间和内存限制
        set_time_limit(0);
        ini_set('memory_limit', -1);
    
        // 清空缓冲区
        ob_end_clean();
    
        // 开启输出缓冲区
        ob_start();
    
        // 设置 Content-Type 和 Content-Disposition 头
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
    
        // 禁止缓存
        header('Cache-Control: no-cache, max-age=0');
        header('Pragma: no-cache');
    
        // 打开输出流
        $fp = fopen('php://output', 'w');
    
        // 写入 BOM 头
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
    
        // 头标题
        fputcsv($fp, $titleArray);
    
        $limt = 10000;
        foreach ($dataArray as $key => $item) {
            
            fputcsv($fp, $item);
            unset($dataArray[$key]);
    
            // 每10000行刷新缓冲区
            if (($key + 1) % $limt === 0) {
                ob_flush();
                flush();
            }
        }
        // 关闭句柄
        fclose($fp);
    
        // 刷新输出缓冲
        ob_end_flush();
    
        exit();
    }
    
    
    • 是否移动端访问访问
    /**
     * 是否移动端访问访问
     *
     * @return bool
     */
    function isMobileClient()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
    
        //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset($_SERVER['HTTP_VIA'])) {
            //找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
    
        //判断手机发送的客户端标志
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = [
                'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp',
                'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu',
                'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi',
                'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile', 'alipay'
            ];
    
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
    
        //协议法,因为有可能不准确,放到最后判断
        if (isset($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
    
        return false;
    }
    
    • 判断是否是微信或者支付宝内置浏览器访问
    /**
     * 判断是否微信内置浏览器访问
     * @return bool
     */
    function isWxClient()
    {
        return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
    }
    
    /**
     * 判断是否支付宝内置浏览器访问
     * @return bool
     */
    function isAliClient()
    {
        return strpos($_SERVER['HTTP_USER_AGENT'], 'Alipay') !== false;
    }
    
    • 数组和XML相互转换
    //数组转xml
    function ArrToXml($arr)
    {
        if (!is_array($arr) || count($arr) == 0) return '';
    
        $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转数组
    function XmlToArr($xml)
    {
        if ($xml == '') return '';
        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }
    
    
    /**
     * 将数组转换为URL参数格式(如:a=1&b=2&c=3)
     * @param array $data 数组
     * @return string URL参数格式字符串
     */
    function toUrlParams($data)
    {
        $buff = '';
        foreach ($data as $k => $v) {
            if ($k != 'sign' && $v != '' && !is_array($v)) {
                $buff .= $k . '=' . $v . '&';
            }
        }
        $buff = trim($buff, '&');
        return $buff;
    }
    
    • 创建流水字符串
    /**
     * 创建流水字符串
     * @param int $length
     * @param bool $allnum
     * @return string
     */
    function createNonceStr($length = 16, $allnum = false)
    {
        if ($allnum) {
            $chars = "01234567890123456789012345678901234567890123456789890123456789";
        } else {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        $str = "";
        $strLength = strlen($chars);
        // 以微秒数作为随机数种子,增加随机性
        mt_srand(microtime(true) * 1000000);
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, $strLength - 1), 1);
        }
        return $str;
    }
    
    function getRandomString($len, $chars = null)
    {
        $bytes = random_bytes($len);
        $result = bin2hex($bytes);
    
        if ($len > strlen($result)) {
            $padLen = $len - strlen($result);
            $padBytes = random_bytes($padLen);
            $result .= bin2hex($padBytes);
        }
    
        return substr($result, 0, $len);
    }
    
    function getRandomString($len, $chars = null)
    {
        $result = '';
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        $bytes = random_bytes($len);
        $lc = strlen($chars) - 1;
        for ($i = 0; $i < $len; ++$i) {
            $result .= $chars[ord($bytes[$i]) % $lc];
        }
    
        return $result;
    }
    
    function getRandomString($len, $chars = null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
    
    
    /**
     * 生成随机字符串
     * @param int $length 长度,默认为32
     * @return string 随机字符串
     */
    function getNonceStr($length = 32)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $nonce_str = '';
        for ($i = 0; $i < $length; $i++) {
            $nonce_str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $nonce_str;
    }
    
    • 生成随机数
    /**
     * @param int $num
     * @return int|string
     */
    function randNum($num = 4)
    {
        $digits = array(mt_rand(1, 9)); // 生成第一个数字
        for ($i = 1; $i < $num; $i++) {
            $digits[] = mt_rand(0, 9); // 生成剩下的数字
        }
        return implode('', $digits);
    }
    
    
    function randNum($num = 4)
    {
        $str = mt_rand(1, 9);
        for ($i = 0; $i < $num - 1; $i++) {
            $str .= mt_rand(0, 9);
        }
        return $str;
    }
    
    • 自定义分页
    /**
     * 利用array_slice自定义分页
     * @param $info  需要分页的数组
     * @param $page  当前页数
     * @param int $pageSize 每页条数
     * @return mixed
     */
    function doPage(array $info, $page, $pageSize = 10)
    {
        $info = array_values((array)$info);
        $total = count($info);
        $start = ($page - 1) * $pageSize;
    
        $data = [];
        $data['total'] = $total;
        $data['current_page'] = $page;
        $data['per_page'] = $pageSize;
        $data['last_page'] = ceil($total / $pageSize);
        $data['data'] = array_slice($info, $start, $pageSize);
    
        return $data;
    }
    
    • php浏览器友好输出
    function ddump($var)
    {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
    
        $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
    
        if (PHP_SAPI !== 'cli') {
            if (!extension_loaded('xdebug')) {
                $output = htmlspecialchars($output, ENT_HTML5 | ENT_SUBSTITUTE, 'UTF-8');
            }
            $output = '<pre>' . $output . '</pre>';
        } else {
            $output = PHP_EOL . $output;
        }
    
        echo $output;
        //exit();
    }
    
    • 判断是否为合法身份证
    /**
     * 判断是否为合法的身份证号码
     * @param $mobile
     * @return int
     */
    function isCreditNo($vStr)
    {
        $vCity = array(
            '11', '12', '13', '14', '15', '21', '22',
            '23', '31', '32', '33', '34', '35', '36',
            '37', '41', '42', '43', '44', '45', '46',
            '50', '51', '52', '53', '54', '61', '62',
            '63', '64', '65', '71', '81', '82', '91'
        );
        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
        if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);
        if ($vLength == 18) {
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        } else {
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }
        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17; $i >= 0; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
            }
            if ($vSum % 11 != 1) return false;
        }
        return true;
    }
    
    • 根据指定字段对二维数组进行排序
    function array_sort($arr, $key, $order = 'asc')
    {
        $new_arr = array();
        foreach ($arr as $k => $v) {
            $new_arr[$k] = $v[$key];
        }
        if ($order == 'asc') {
            asort($new_arr);
        } else {
            arsort($new_arr);
        }
        $result_arr = array();
        foreach ($new_arr as $k => $v) {
            $result_arr[] = $arr[$k];
        }
        return $result_arr;
    }
    
    • 随机生成唯一订单号不重复
    /**
     * 随机生成唯一订单号不重复
     * @param $business_id  订单id
     * @param int $leng 生成订单号的长度
     * @param string $algo 哈希算法:sha256或者sha512
     * @param string $prefix 订单前缀
     * @param string $suffix 订单后缀
     * @return bool|string
     */
    function generate_order_number($business_id, $leng = 16, $algo = 'sha256', $prefix = 'ORDER', $suffix = '')
    {
        // 生成一个唯一的随机数
        $random = mt_rand(100000, 999999);
    //    $random = random_int(100000, 999999);
    
        // 获取当前时间戳的毫秒数
        $millisecond = round(microtime(true) * 100000);
    
        // 计算哈希值生成一个64位随机字符串,用于保证唯一性
        $hash = hash($algo, $prefix . $business_id . $millisecond . $random);
    
        // 截取哈希值的前16位作为订单号
        $order_number = substr($hash, 0, $leng);
    
        // 添加一个随机的后缀,增加订单号唯一
        $order_number .= mt_rand(10, 99) . $suffix;
    
        return $order_number;
    }
    

    二维数组转字符串

    /**
     * 二维数组转字符串
     * @param $arr
     * @return bool|string
     */
    function arr_to_str($arr)
    {
        $t = '';
        foreach ($arr as $v) {
            $v = implode(",", $v); // 可以用implode将一维数组转换为用逗号连接的字符串
            $temp[] = $v;
        }
        foreach ($temp as $v) {
            $t .= $v . ",";
        }
        $t = substr($t, 0, -1); // 利用字符串截取函数消除最后一个逗号
        return $t;
    }
    
    /**
     * 二维数组转字符串
     * @param $array
     * @return string
     */
    function arrayToString($array)
    {
        $output = '';
        foreach ($array as $row) {
            $output .= implode(',', $row) . ',';
        }
        return rtrim($output, ',');
    }
    

    获取服务端IP

    /**
     * 获取服务器ip
     * @return array|false|mixed|string
     */
    function getServerIp()
    {
        if (isset($_SERVER)) {
            if ($_SERVER['SERVER_ADDR']) {
                $server_ip = $_SERVER['SERVER_ADDR'];
            } else {
                $server_ip = $_SERVER['LOCAL_ADDR'];
            }
        } else {
            $server_ip = getenv('SERVER_ADDR');
        }
        if ($server_ip == '::1') {
            //本地
            $server_ip = '127.0.0.1';
        }
        return $server_ip;
    }
    
    • 判断是否json格式
    /**
     * 判断是否json格式
     * @param $str
     * @return bool
     */
    function is_valid_json(string $str)
    {
        if (is_numeric($str)) {
            return false;
        }
        json_decode($str);
        return json_last_error() === JSON_ERROR_NONE;
    }
    
    • 过滤请求参数防止xss和sql注入
    /**
     * @param $params
     * @return array|string|string[]|null
     */
    function filter_input_params($params)
    {
        // 定义各种正则表达式,用于过滤危险输入
        $filter_arr = array(
            // 过滤 HTML 标签
            '/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU',
            // 过滤 JavaScript 事件
            '/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU',
            // 过滤 SQL 注入字符
            '/select\b|and\b|or\b|like\b|regexp\b|from\b|where\b|update\b|insert\b|exec\b|order\s*by|having\b|drop\b|delete\b|\(|\)|\[|\]|\||<|>|;|:|&|\'|\"|%|\+|-|_|=|\*|\\\\|union|into|load_file|outfile|dump/is',
            // 过滤参数中的 URL,不过建议使用专门的 URL 过滤函数或第三方库
            '/(^|[^\\w])(https?:\\/\\/[^\\s]+)([^\\w]|$)/i',
            // 过滤ASCII码大于127的非法字符
            '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u',
            // 过滤不可见字符(制表符(Tab)、回车符(CR)、换行符(LF)等)
            '/\p{Cc}+/u'
        );
        if (is_array($params)) {
            array_walk_recursive($params, function (&$v) use ($filter_arr) {
                if (!is_numeric($v)) {
                    if (filter_var($v, FILTER_VALIDATE_URL)) {
                        $v = filter_var($v, FILTER_SANITIZE_URL);
                    } elseif (filter_var($v, FILTER_VALIDATE_EMAIL)) {
                        $v = filter_var($v, FILTER_SANITIZE_EMAIL);
                    } else {
                        $v = strip_tags($v); // 过滤 HTML 标签
                        $v = preg_replace($filter_arr, '', $v); // 去除危险字符
                    }
                    $v = trim($v);
                }
            });
        } else {
            if (!is_numeric($params)) {
                if (filter_var($params, FILTER_VALIDATE_URL)) {
                    $params = filter_var($params, FILTER_SANITIZE_URL);
                } elseif (filter_var($params, FILTER_VALIDATE_EMAIL)) {
                    $params = filter_var($params, FILTER_SANITIZE_EMAIL);
                } else {
                    $params = strip_tags($params); // 过滤 HTML 标签
                    $params = preg_replace($filter_arr, '', $params); // 去除危险字符
                }
                $params = trim($params); // 去除空格
            }
        }
        return $params;
    }
    
    • 远程下载文件
    /**
     * @param $url  远程地址:"http://www.baidu.com/img/baidu_jgylogo3.gif"
     * @param $path 本地保存目录:/www/wwwroot/dow/
     * @return bool
     */
    function download_file($url, $path)
    {
        // 检查路径是否存在,如果不存在则创建
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
    
        // 解码URL中的文件名
        $decoded_file = urldecode(basename($url));
    
        // 拼接文件路径
        $file_path = $path . mb_convert_encoding($decoded_file, "GB2312", "UTF-8");
    
        // 初始化 curl 会话
        $ch = curl_init();
    
        // 设置要请求的 URL
        curl_setopt($ch, CURLOPT_URL, $url);
    
        // 设置请求超时时间(单位:秒)
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
    
        // 设置输出文件流
        curl_setopt($ch, CURLOPT_FILE, fopen($file_path, 'w+'));
    
        // 开启重定向跟踪功能
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
        // 执行 curl 请求
        $result = curl_exec($ch);
    
        // 获取 HTTP 状态码
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        // 关闭 curl 会话
        curl_close($ch);
    
        // 如果请求失败或HTTP状态码不是200,删除该文件并返回false
        if ($result === false || $httpcode !== 200) {
            unlink($file_path);
            return false;
        }
    
        // 返回true表示下载成功
        return true;
    }
    
    • 补齐缺失日期时间(配合前端柱状图、折线图)
    /**
     * 补齐时间日期
     * 使用案例:统计报表,折线图,柱状图
     * @param $startDate 开始时间
     * @param $endDate 结束时间
     * @param array $dates 
     * @param string $interval 天:day,小时:hours,分钟:minutes,秒:seconds
     * @param string $format 
     * @return array
     */
    function fill_date($startDate, $endDate, array $dates = array(), $interval = '1 day', $format = 'Y-m-d H:i:s')
    {
        $allDates = array();
        $currentDate = strtotime($startDate);
        $endDate = strtotime($endDate);
    
        while ($currentDate <= $endDate) {
            $dateString = date($format, $currentDate);
            $allDates[] = $dateString;
            $currentDate = strtotime('+' . $interval, $currentDate);
        }
    
        if ($dates) {
            $allDates = array_diff($allDates, $dates);
        }
    
        return array_values($allDates);
    }
    
    • 两个二维数组根据数组中的Key合并成一个新的二维数组
    /**
     * 两个二维数组根据数组中的Key合并成一个新的二维数组
     * @param $callStats
     * @param $qualityStats
     * @param $keys
     * @return array
     */
    function mergeArraysByAgentName($callStats, $qualityStats, $keys)
    {
        $mergedArray = [];
    
        $qualityDataMap = [];
    
        foreach ($qualityStats as $qualityData) {
            $agentName = $qualityData[$keys];
            $qualityDataMap[$agentName] = $qualityData;
        }
    
        foreach ($callStats as $callData) {
            $agentName = $callData[$keys];
    
            if (isset($qualityDataMap[$agentName])) {
                $qualityData = $qualityDataMap[$agentName];
                $mergedData = array_merge($callData, $qualityData);
                $mergedArray[] = $mergedData;
            }
        }
    
        return $mergedArray;
    }
    
    • 无限分类
    /**
     * 引用无限分类
     * @param array $list
     * @param string $pIdkey
     * @return array
     */
    function generateTree(array $list, $pIdkey = 'pid')
    {
        $items = [];
        foreach ($list as $v) {
            $items[$v['id']] = $v;
            $items[$v['id']]['children'] = [];
        }
    
        $tree = [];
        foreach ($items as &$item) {
            if (isset($items[$item[$pIdkey]])) {
                $items[$item[$pIdkey]]['children'][] = &$item;
            } else {
                $tree[] = &$item;
            }
        }
        unset($item);
    
        return $tree;
    }
    
    • tree树形数组转列表
    /**
     * tree树形数组转列表二维数组
     * @param $tree 树形数组
     * @param string $child
     * @param string $order
     * @param array $list
     * @return array
     */
    function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array())
    {
        if (is_array($tree)) {
            foreach ($tree as $key => $value) {
                $reffer = $value;
                if (isset($reffer[$child])) {
                    unset($reffer[$child]);
                    tree_to_list($value[$child], $child, $order, $list);
                }
                $list[] = $reffer;
            }
        }
        return $list;
    }
    
    • 友好时间显示
    /**
     * 友好时间显示
     * @param $time 时间戳
     * @return bool|string
     */
    function format_date($time)
    {
        if (!$time) {
            return false;
        }
    
        $currentTimestamp = time();
        $timestamp = intval($time);
    
        $diffSeconds = $currentTimestamp - $timestamp;
        $diffDays = floor(($currentTimestamp - strtotime('today')) / (60 * 60 * 24));
    
        if ($diffSeconds <= 0) {
            return '刚刚';
        } elseif ($diffSeconds < 60) {
            return $diffSeconds . '秒前';
        } elseif ($diffSeconds < 3600) {
            return floor($diffSeconds / 60) . '分钟前';
        } elseif ($diffDays <= 2) {
            $formattedTime = date('H:i', $timestamp);
            if ($diffDays == 0) {
                return '今天' . $formattedTime;
            } elseif ($diffDays == 1) {
                return '昨天' . $formattedTime;
            } else {
                return '前天' . $formattedTime;
            }
        } elseif ($diffDays <= 30) {
            return date('m月d日 H:i', $timestamp);
        } elseif ($diffDays <= 365) {
            return date('m月d日', $timestamp);
        } else {
            return date('Y年m月d日', $timestamp);
        }
    }
    
    • 字符串截取,支持中文和其他编码
    /**
     * 字符串截取,支持中文和其他编码
     * @static
     * @access public
     * @param string $str 需要转换的字符串
     * @param string $start 开始位置
     * @param string $length 截取长度
     * @param string $charset 编码格式
     * @param string $suffix 截断显示字符
     * @return string
     */
    function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
    {
        if (function_exists("mb_substr")) {
            $slice = mb_substr($str, $start, $length, $charset);
        } elseif (function_exists('iconv_substr')) {
            $slice = iconv_substr($str, $start, $length, $charset);
            if (false === $slice) {
                $slice = '';
            }
        } else {
            $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("", array_slice($match[0], $start, $length));
        }
        if (strlen($slice) == strlen($str)) {
            return $slice;
        } else {
            return $suffix ? $slice . '...' : $slice;
        }
    }
    
    
    • 计算倒计时
    /**
     * @param $targetDateTime
     * @param string $currentTime
     * @return string
     */
    function countdown($targetDateTime, $currentTime = '')
    {
        // 获取目标日期和时间的时间戳
        if (is_numeric($targetDateTime)) {
            $targetTimestamp = $targetDateTime;
        } else {
            $targetTimestamp = strtotime($targetDateTime);
        }
    
        // 获取当前日期和时间的时间戳
        if (empty($currentTime)) {
            $currentTimestamp = time();
        } else {
            if (!is_numeric()) {
                $currentTimestamp = strtotime($currentTime);
            }
            $currentTimestamp = $currentTime;
        }
    
        // 计算时间差,以秒为单位
        $difference = $targetTimestamp - $currentTimestamp;
    
        // 将时间差转换为小时、分钟和秒数
        $hours = floor($difference / (60 * 60));
        $minutes = floor(($difference % (60 * 60)) / 60);
        $seconds = $difference % 60;
    
        // 输出倒计时结果
        return "距离目标时间还有:$hours 小时, $minutes 分钟, $seconds 秒";
    }
    //使用示例
    $targetDateTime = '2023-12-31 23:59:59';  // 假设目标日期为2023年12月31日 23时59分59秒
    countdown($targetDateTime);
    

    相关文章

      网友评论

          本文标题:php 自定义公共函数 2023-02-07

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