php一些帮组函数
dio 2018-07-23 php
# 代码如下
/**
* 匹配手机号码
*/
function phoneMatching($phone)
{
if (preg_match("/^1\d{10}$/", $phone)) {
return true;
}
return false;
}
/**
* 获取用户真实 ip
* @return array|false|mixed|string
*/
function getClientIp()
{
if (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
}
if (getenv('HTTP_X_REAL_IP')) {
$ip = getenv('HTTP_X_REAL_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
$ips = explode(',', $ip);
$ip = $ips[0];
} elseif (getenv('REMOTE_ADDR')) {
$ip = getenv('REMOTE_ADDR');
} else {
$ip = '0.0.0.0';
}
return $ip;
}
//生成验证码
function code()
{
$str = '0123456789';
return substr(str_shuffle($str), 0, 6);
}
//yii2.0 找出log中出现最多的前10sql
function yiiSql()
{
// 获取所有的 SQL 查询语句,并统计数量
// 获取日志文件路径
$logPath = \Yii::$app->getRuntimePath() . '/logs/2023-05-19/db.txt.1';
// 读取日志文件内容
$logContent = file_get_contents($logPath);
// 匹配出所有的 SQL 语句
$pattern = '/SELECT.*?FROM\s*\S+|INSERT.*?INTO\s*\S+|UPDATE\s*\S+\s*SET\s*|DELETE\s*FROM\s*\S+/is';
preg_match_all($pattern, $logContent, $matches);
// 统计 SQL 语句出现次数
$count = [];
foreach ($matches[0] as $sql) {
$count[$sql] = isset($count[$sql]) ? $count[$sql] + 1 : 1;
}
// 对 SQL 查询语句出现次数进行排序,并取出前 10 条
arsort($count);
$top10 = array_slice($count, 0, 10);
foreach ($top10 as $sql11 => $num) {
echo "SQL 语句:" . $sql11 . ",出现了 $num 次。\n";
}
}
//初步整理 api log中响应速度慢的接口
function exexTime(){
// 获取所有的 SQL 查询语句,并统计数量
// 获取日志文件路径
$logPath = \Yii::$app->getRuntimePath() . '/logs/2023-05-19/2023-05api_requests (1).log';
// 读取日志文件内容
$input_string = file_get_contents($logPath);
// 假设 $input_string 是字符串输入
$matches = [];
// 匹配所有 path 相关接口代码
preg_match_all('/"path":"(.+?)"/', $input_string, $paths);
// 匹配所有 execution_time 相关接口代码
preg_match_all('/"execution_time":"(.+?)ms"/', $input_string, $exec_times);
// 将结果按 execution_time 从大到小排序
arsort($exec_times[1]);
dd($exec_times[1]);
$top_10_matches = array_slice($exec_times[1], 0, 30,true);
$mss = [];
foreach ($top_10_matches as $kkk=>$vvv){
$mss[$vvv] = $paths[1][$kkk] ?? '';
}
dd($top_10_matches,$mss);
}
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88