wxvirus wxvirus
首页
  • Go文章

    • Go语言学习
  • Rust

    • Rust学习
  • Java

    • 《Java》
  • Python文章

    • Python
  • PHP文章

    • PHP设计模式
  • 学习笔记

    • 《Git》
  • HTML
  • CSS
  • JS
  • 技术文档
  • GitHub技巧
  • 刷题
  • 博客搭建
  • 算法学习
  • 架构设计
  • 设计模式
  • 学习
  • 面试
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

无解的lifecycle

let today = new Beginning()
首页
  • Go文章

    • Go语言学习
  • Rust

    • Rust学习
  • Java

    • 《Java》
  • Python文章

    • Python
  • PHP文章

    • PHP设计模式
  • 学习笔记

    • 《Git》
  • HTML
  • CSS
  • JS
  • 技术文档
  • GitHub技巧
  • 刷题
  • 博客搭建
  • 算法学习
  • 架构设计
  • 设计模式
  • 学习
  • 面试
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • C&C++

  • PHP

    • PHP基础或常见方法

    • Laravel

    • ThinkPHP

      • 全局异常处理类
      • 公共函数
        • 格式化文件大小
        • 可逆加密算法 encrypt
        • 解密算法 decrypt
        • 导出Excel
        • 无限极分类树
        • 系统邮件发送函数
        • 获取当前url地址
        • 截取多少长度的字符串并以省略号代替超过的部分
        • Api请求curl方式
        • HTTP curl请求API方法
        • 获取当前日期是星期几
    • PHP多进程编程

    • swoole

  • Python

  • Go

  • microservice

  • rust

  • Java

  • 学习笔记

  • 后端
  • PHP
  • ThinkPHP
wxvirus
2021-10-21

公共函数

# 我觉得有点用的公共函数(I think it's a little bit useful)


# 格式化文件大小

/**
 * [format_size 格式化文件大小]
 * @param  [int] $size [文件大小]
 * @return [float/double]       [格式化后的文件大小]
 */
function format_size($size) {
	$arr = ['B', 'KB', 'M', 'G', 'T', 'P'];
	$i = 0;
	while ($size >= 1024) {
		$size = $size / 1024;
		$i++;
	}
	// 四舍五入进行返回
	return round($size, 4).$arr[$i];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 可逆加密算法 encrypt

/**
 * [encrypt 可逆加密算法]
 * @param  [type] $data [description]
 * @param  [type] $key  [description]
 * @return [type]       [description]
 */
function encrypt($data, $key) {
	$key = md5($key);
	$x = 0;
	$len = strlen($data);
	$l = strlen($data);
	$char = '';
	$str = '';
	for ($i=0; $i < $len; $i++) { 
		if ($x == $l) {
			$x = 0;
		}
		$char .= $key{$x};
		$x++;
	}
	for ($i = 0; $i < $len; $i++) {
		$str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
	}
	return base64_encode($str);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 解密算法 decrypt

/**
 * [decrypt 解密算法]
 * @param  [type] $data [description]
 * @param  [type] $key  [description]
 * @return [type]       [description]
 */
function decrypt($data, $key) {
	$key = md5($key);
	$x = 0;
	$data = base64_decode($data);
	$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 $str;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

# 导出Excel

// 导出excle
function export_to($data,$name=false,$type = 0){
    if(!$name){$name=date("Y-m-d-H-i-s",time());}
    $PHPExcel = new PHPExcel(); //实例化PHPExcel类,类似于在桌面上新建一个Excel表格
    $PHPExcel->getActiveSheet()->fromArray($data);
    $PHPExcel->getActiveSheet()->setTitle('Sheet1'); //给当前活动sheet设置名称
    $PHPExcel->setActiveSheetIndex(0);
    $fileName = './public/'.date('Y-m-d_', time()).time().'.xlsx';
    $saveName = $name.date('Y-m-d', time()).'.xlsx';

    $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel5');//按照指定格式生成Excel文件,‘Excel2007’表示生成2007版本的xlsx,‘Excel5’表示生成2003版本Excel文件
    if ($type == 0) {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header('Content-Disposition: attachment;filename="'.$saveName.'"');//告诉浏览器输出浏览器名称
        // header('Content-Disposition: attachment;filename="01simple.xlsx"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $PHPWriter->save("php://output");
    }else{
        $PHPWriter->save($fileName); //表示在$path路径下面生成demo.xlsx文件
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 无限极分类树

function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $keys = 'id', $sort = 'asc', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $list[$key][$child] = [];
            $refer [$data[$pk]] = &$list[$key];
        }

        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree [] = &$list[$key];
                $tree = my_sort($tree,$keys,$sort,SORT_NUMERIC);
            } else {
                if (isset ($refer [$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child] [] = &$list[$key];
                    $parent[$child] = my_sort($parent[$child],$keys,$sort,SORT_NUMERIC);
                }
            }
        }
    }
    return $tree;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# 系统邮件发送函数

/**
 * 系统邮件发送函数
 * @param string $tomail 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author static7 <static7@qq.com>
 使用方法:
$toemail='111111@qq.com';  
$name = 'dqwdqqwdq';//收件人昵称
$subject='注册验证码';
$mail_tpl = model('MailTpl')->where('type', 'register')->find()->toArray();
$content = str_replace("\$code","123456",$mail_tpl['content']);
$result = send_mail($toemail,$name,$subject,$content);
dump($result);
 */
function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {
    $config_mail = model('Mail')->find()->toArray();
    $shop = model('Config')->find();
    $mail = new \PHPMailer();           //实例化PHPMailer对象
    
    $mail->CharSet = 'UTF-8';           //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
    if($config_mail['secure']){
        $mail->SMTPSecure = 'ssl';      // 使用安全协议Enable TLS encryption, `ssl` also accepted
    }else{
        $mail->SMTPSecure = 'tls';      // 使用安全协议Enable TLS encryption, `ssl` also accepted
    }
    $mail->Host = $config_mail['host']; // SMTP 服务器
    $mail->Port = $config_mail['port'];                  // SMTP服务器的端口号
    $mail->Username = $config_mail['user'];    // SMTP服务器用户名
    $mail->Password = $config_mail['pass'];     // SMTP服务器密码
    $mail->SetFrom($config_mail['user'], $shop['title']);
    $replyEmail = $config_mail['replyTo'];                   //留空则为发件人EMAIL
    $replyName = '发送回复';                    //回复名称(留空则为发件人名称)
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# 获取当前url地址

/**
 * [getActionUrl description]获取当前url
 * @return [type] [description]
 */
function getActionUrl(){
    $module = strtolower(request()->module());
    $controller = strtolower(request()->controller());
    $action = strtolower(request()->action());
    return $module.'/'.$controller.'/'.$action;
}
1
2
3
4
5
6
7
8
9
10

# 截取多少长度的字符串并以省略号代替超过的部分

if (!function_exists('strCut')) {
    function strCut($str, $length)//$str为要进行截取bai的字符串,$length为截取长度(du汉字算一个字,字母算半个字)zhi
    {
        $str = trim($str);
        $string = "";
        if (strlen($str) > $length) {
            for ($i = 0; $i < $length; $i++) {
                if (ord($str) > 127) {
                    $string .= $str[$i] . $str[$i + 1] . $str[$i + 2];
                    $i = $i + 2;
                } else {
                    $string .= $str[$i];
                }
            }
            $string .= "...";
            return $string;
        }
        return $str;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# Api请求curl方式

if (!function_exists('api')) {
    /**
     * @param string $url
     * @param string $params
     * @param string $method
     * @param array $header
     * @throws \Exception
     * @return
     */
    function api(string $url, string $params = '', string $method = 'GET', array $header = array())
    {
        $opts = array(
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_SSL_VERIFYHOST => FALSE,
            CURLOPT_SSL_VERIFYPEER => FALSE,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_HEADER => FALSE
        );
        switch(strtoupper($method)){
            case 'GET':
                $opts[CURLOPT_URL] = $url.'?';
                if (!empty($params)) {
                    $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                }
                break;
            case 'POST':
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = TRUE;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
        }
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $result = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error){
            throw new Exception('curl执行出错');
        }

        return $result;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

# HTTP curl请求API方法

if (!function_exists('httpRequest')) {
    function httpRequest($url, $method, $postfields = null, $headers = [], $debug = false)
    {
        $method = strtoupper($method);
        $ci     = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? true : false;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response    = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code   = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        
        return $response;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

# 获取当前日期是星期几

if (!function_exists('getTimeWeek'))
{
    /**
     * 获取当前时间是星期几
     * @param $time   [当前时间戳]
     * @param int $i  [第几天之后 默认为0为今天]
     * @return mixed
     */
    function getTimeWeek($time, $i = 0)
    {
        $weekArray = [7, 1, 2, 3, 4, 5, 6];
        $oneDay = 24 * 60 * 60;
        return $weekArray[date('w', $time + $oneDay * $i)];
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
编辑 (opens new window)
上次更新: 2021/10/21, 20:43:49
全局异常处理类
程序与进程

← 全局异常处理类 程序与进程→

最近更新
01
vue3配合vite初始化项目的一些配置
07-26
02
网盘系统开发学习
07-24
03
linux多进程
06-19
更多文章>
Theme by Vdoing | Copyright © 2021-2024 wxvirus 苏ICP备2021007210号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式