Utils.php
13.8 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
<?php
namespace common\helpers;
use Yii;
use common\exts\Http;
use Faker\Provider\Uuid;
class Utils
{
private static $vKey = 'thisisakey0olk2i8suwjshwks';
public static function getVKey()
{
return self::$vKey;
}
public static function ceiling($number, $significance = 1)
{
return (is_numeric($number) && is_numeric($significance)) ? (ceil($number / $significance) * $significance) : false;
}
public static function clientIp()
{
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
$ip = getenv("HTTP_CLIENT_IP");
} else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
$ip = getenv("HTTP_X_FORWARDED_FOR");
} else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
$ip = getenv("REMOTE_ADDR");
} else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = "unknown";
}
return $ip;
}
/** 生成随机字符串
* @param $len
* @param bool|false $onlyNumber 是否纯数字
* @return string
*/
public static function rand($len, $onlyNumber = false)
{
$randString = '';
$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz_";
if($onlyNumber == true){
$strPol = '0123456789';
}
$max = strlen($strPol) - 1;
for($index=0; $index < $len; $index++){
$randString .= $strPol[rand(0, $max)]; // rand($min,$max)生成介于min和max两个数之间的一个随机整数
}
return $randString;
}
/** 生成随机用户昵称: 3个小写字母+9位数字
* @param $len
* @return string
*/
public static function randNickname()
{
$randString = '';
// 3个字母
$strPol = "abcdefghijklmnopqrstuvwxyz";
$max = strlen($strPol) - 1;
for($index = 0; $index < 3; $index++) {
$randString .= $strPol[rand(0, $max)];
}
// + 9位数字
$strPol = "0123456789";
$max = strlen($strPol) - 1;
for($index = 0; $index < 8; $index++) {
$randString .= $strPol[rand(0, $max)];
}
return $randString;
}
/**
* 生成随机注册码数字串
* @return string
*/
public static function randRegCode($len)
{
$randString = '';
$strPol = "0123456789";
$max = strlen($strPol) - 1;
for($index=0; $index < $len; $index++){
$randString .= $strPol[rand(0, $max)]; // rand($min,$max)生成介于min和max两个数之间的一个随机整数
}
return $randString;
}
/** 用来验证签名
* @param $sign
* @param $revFromOpenId
* @param $location
* @param $tt
* @return bool
*/
public static function checkSign($sign,$arr){
if(empty($sign) || empty($arr)) return false;
//ksort($arr);
//$mySign = self::ToUrlParams($arr);
$mySign = self::genSign($arr);
if($sign == $mySign){
return true;
}else{
return false;
}
}
/**
* @param $revFromOpenId
* @param $location
* @return string
*/
public static function genSign($arr){
if(empty($arr)){return null;}
ksort($arr);
$str = self::ToUrlParams($arr);
$mySign = md5($str.'&key='.self::$vKey);
return $mySign;
}
/**
*
* 拼接签名字符串
* @param array $urlObj
*
* @return 返回已经拼接好的字符串
*/
private static function ToUrlParams($urlObj)
{
$buff = "";
foreach ($urlObj as $k => $v)
{
if($k != "sign"){
if( !is_bool($v) && !is_int($v) && !is_integer($v) && !is_numeric($v) && !is_string($v)){
$v = json_encode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
return $buff;
}
/**
* 获取指定数值范围的随机浮点数
* @param int $min
* @param int $max
* @return int
*/
public static function getRandomFloat($min = 0, $max = 1)
{
$number = $min + mt_rand() / mt_getrandmax() * ($max - $min);
return round($number ,2);
}
/** 经纬度检测是否合格
* @param $latitude
* @param $longitude
* @return bool
*/
static function isValidCoordinate($latitude, $longitude)
{
//经度最大是180° 最小是0°
if (0.0 >= $longitude || 180.0 < $longitude) {
return false;
}
//纬度最大是90° 最小是0°
if (0.0 >= $latitude || 90.0 < $latitude) {
return false;
}
return true;
}
/** 产生不带 - 的
* @param $len
* @return string
*/
public static function genUUID()
{
$uuid = Uuid::uuid();
$uuid = str_replace('-','',$uuid);
return $uuid;
}
/**
* 上周一
* @$timestamp ,某个星期的某一个时间戳,默认为当前时间
* @is_return_timestamp ,是否返回时间戳,否则返回时间格式
* */
public static function lastMonday($timestamp=0, $is_return_timestamp=true)
{
static $cache ;
$id = $timestamp.$is_return_timestamp;
if (!isset($cache[$id])) {
if(!$timestamp) $timestamp = time();
$thismonday = self::thisMonday($timestamp) - /*7*86400*/604800;
if ($is_return_timestamp) {
$cache[$id] = $thismonday;
} else {
$cache[$id] = date('Y-m-d',$thismonday);
}
}
return $cache[$id];
}
/**
* 上个星期天
* @$timestamp ,某个星期的某一个时间戳,默认为当前时间
* @is_return_timestamp ,是否返回时间戳,否则返回时间格式
* */
public static function lastSunday($timestamp = 0, $is_return_timestamp = true)
{
static $cache ;
$id = $timestamp.$is_return_timestamp;
if (!isset($cache[$id])) {
if(!$timestamp) $timestamp = time();
$thissunday = self::thisSunday($timestamp) - /*7*86400*/604800;
if ($is_return_timestamp) {
$cache[$id] = $thissunday;
} else {
$cache[$id] = date('Y-m-d', $thissunday);
}
}
return $cache[$id];
}
/**
* 这个星期的星期一
* @param int @$timestamp ,某个星期的某一个时间戳,默认为当前时间
* @param bool $is_return_timestamp 是否返回时间戳,否则返回时间格式
* @return mixed
*/
static function thisMonday($timestamp = 0, $is_return_timestamp = true)
{
static $cache ;
$id = $timestamp.$is_return_timestamp;
if (!isset($cache[$id])) {
if(!$timestamp) $timestamp = time();
$monday_date = date('Y-m-d', $timestamp-86400*date('w',$timestamp)+(date('w',$timestamp)>0?86400:-/*6*86400*/518400));
if ($is_return_timestamp) {
$cache[$id] = strtotime($monday_date);
} else {
$cache[$id] = $monday_date;
}
}
return $cache[$id];
}
/**
* 这个星期的星期天
* @$timestamp ,某个星期的某一个时间戳,默认为当前时间
* @is_return_timestamp ,是否返回时间戳,否则返回时间格式
* */
static function thisSunday($timestamp = 0, $is_return_timestamp = true)
{
static $cache ;
$id = $timestamp.$is_return_timestamp;
if(!isset($cache[$id])){
if(!$timestamp) $timestamp = time();
$sunday = self::thisMonday($timestamp) + /*6*86400*/518400;
if($is_return_timestamp){
$cache[$id] = $sunday;
}else{
$cache[$id] = date('Y-m-d',$sunday);
}
}
return $cache[$id];
}
/** 验证是否为手机号码
* @param $phone
* @return bool\
*/
static function isPhone($phone)
{
if (preg_match("/^(86)?1[3456789]\d{9}$/", $phone)) {
return true;
} else {
return false;
}
}
/**
* 把unicode转化成中文
* @param $str
* @return mixed
*/
public static function decodeUnicode($str)
{
return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
create_function(
'$matches',
'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
),
$str);
}
/** 邮箱验证
* @param $email
* @return bool
*/
public static function isEmail($email)
{
if (preg_match("/^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$/i" , $email)) {
return true;
} else {
return false;
}
}
/**
* 通过IP地址获取IP所在城市
* @param $ipAddress
* @return array|mixed
*/
public static function getAddressByIPAddress($ipAddress)
{
if (!isset(Yii::$app->params['GD_KEY']) || empty(Yii::$app->params['GD_KEY'])) {
return [];
}
$gdKey = Yii::$app->params['GD_KEY'];
$content = Http::get("https://restapi.amap.com/v3/ip?ip={$ipAddress}&output=json&key=" . $gdKey);
$json = array();
if ($content) {
$json = json_decode($content, true);
}
return $json;
}
/**
* 获取客户端IP地址
* @return mixed
*/
public static function getClientUserIpAddress()
{
if (isset(\yii::$app->request->userIP)) {
return \yii::$app->request->userIP;
} else {
return '0000';
}
}
public static function getBrowserAgent()
{
if (isset(\yii::$app->request->userAgent)) {
return \yii::$app->request->userAgent;
} else {
return null;
}
}
/** java 带T和带Z的时间格式换成PHP
* @param $str
* @return bool|null|string
*/
static function coverTimeStampToPHP($str)
{
$timeZone = 8;
//"2018-09-03T08:16:18.563Z"
if (empty($str)) {
return null;
}
if (strpos($str, 'T') == false || substr($str, -1) != 'Z' ) {
return false;
}
$str = str_replace("T", "", $str);
$str = str_replace("Z", "", $str);
$time = strtotime($str." +{$timeZone} hours");
return date('Y-m-d H:i:s', $time);
}
/** php 日期格式转化为 带T和带Z的格式
* @param $str
* @return bool|null|string
*/
static function coverTimeStampToJava($str = '')
{
$timeZone = 8;
if (empty($str)) {
return date('Y-m-d\TH:i:s\Z',time()-($timeZone * 3600));
}
$t = strtotime($str." -{$timeZone} hours");
$newStr = date('Y-m-d\TH:i:s\Z', $t);
return $newStr;
}
/**
* 字节大小转化为字符串显示格式: 1KB, 1MB...
* @param $size
* @return string
*/
public static function formatBytes($size) {
$units = array(' B', ' KB', ' MB', ' GB', ' TB');
for ($i = 0; $size >= 1024 && $i < 4; $i++) {
$size /= 1024;
}
return round($size, 2) . $units[$i];
}
/**
* 将字符串格式(如: "64M" or "30" )转换成整数字节数
* @param mixed $size
* @return int
*/
public static function normalizeBytesInt($size)
{
if (is_string($size)) {
switch (substr($size, -1)) {
case 'M': case 'm': return intval($size) * 1048576;
case 'K': case 'k': return intval($size) * 1024;
case 'G': case 'g': return intval($size) * 1073741824;
}
}
return (int) $size;
}
/**
* 获取秒数对应的天/时/分
* @param $time
* @return string
*/
public static function getTimesDayHourMin($time)
{
$d = floor($time / (3600 * 24));
$h = floor(($time % (3600 * 24)) / 3600);
$m = floor((($time % (3600 * 24)) % 3600) / 60);
if ($d > '0') {
return $d . '天' . $h . '小时' . $m . '分';
} else {
if ($h != '0') {
return $h . '小时' . $m . '分';
} else {
return $m . '分';
}
}
}
/**
* 生成mac 地址
* @return string
*/
static function macGenerate()
{
$adrArray = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" ];
$returnMAC = '';
for($i = 1; $i < 13 ; $i++) {
$index = 0;
if ($i != 2) {
$index = mt_rand(0, 15);
} else {
//第二位只能是偶数
$indexArray = [0, 2, 4, 6, 8, 10, 12, 14];
$index = $indexArray[mt_rand(0, 7)];
}
$returnMAC = $returnMAC . $adrArray[$index];
}
return self::coverToMacAddress($returnMAC);
}
/**
* 把mac地址转化为带:的字符串
* @param $macStr
* @return string
*/
static function coverToMacAddress($macStr)
{
if (empty($macStr)) {
return null;
}
$macSplitArr = str_split($macStr, 2);
$returnStr = implode(":", $macSplitArr);
return $returnStr;
}
/**
* @param $mac
* @return bool
*/
static function isMacAddress($mac)
{
if(preg_match('/^([0-9a-fA-F]{2})(([:|-]{0,1}[0-9a-fA-F]{2}){5})$/', $mac)) {
return true;
} else {
return false;
}
}
}