common.php
10.5 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
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件
use think\Request;
use think\Log;
/**
* 打印调试函数
* @param $content
* @param $is_die
*/
function pre($content, $is_die = true)
{
header('Content-type: text/html; charset=utf-8');
echo '<pre>' . print_r($content, true);
$is_die && die();
}
/**
* 驼峰命名转下划线命名
* @param $str
* @return string
*/
function toUnderScore($str)
{
$dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
return '_' . strtolower($matchs[0]);
}, $str);
return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
}
/**
* 生成密码hash值
* @param $password
* @return string
*/
function api_hash($password)
{
return md5(md5($password) . 'api_salt_SmTRx');
}
/**
* 获取当前域名及根路径
* @return string
*/
function base_url()
{
static $baseUrl = '';
if (empty($baseUrl)) {
$request = Request::instance();
$subDir = str_replace('\\', '/', dirname($request->server('PHP_SELF')));
$baseUrl = $request->scheme() . '://' . $request->host() . $subDir . ($subDir === '/' ? '' : '/');
}
return $baseUrl;
}
/**
* 写入日志 (使用tp自带驱动记录到runtime目录中)
* @param $value
* @param string $type
*/
function log_write($value, $type = 'api-info')
{
$msg = is_string($value) ? $value : var_export($value, true);
Log::record($msg, $type);
}
/**
* curl请求指定url (get)
* @param $url
* @param array $data
* @return mixed
*/
function curl($url, $data = [])
{
// 处理get数据
if (!empty($data)) {
$url = $url . '?' . http_build_query($data);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
/**
* curl请求指定url (post)
* @param $url
* @param array $data
* @return mixed
*/
function curlPost($url, $data = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/**
* 多维数组合并
* @param $array1
* @param $array2
* @return array
*/
function array_merge_multiple($array1, $array2)
{
$merge = $array1 + $array2;
$data = [];
foreach ($merge as $key => $val) {
if (
isset($array1[$key])
&& is_array($array1[$key])
&& isset($array2[$key])
&& is_array($array2[$key])
) {
$data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
} else {
$data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
}
}
return $data;
}
/**
* 二维数组排序
* @param $arr
* @param $keys
* @param bool $desc
* @return mixed
*/
function array_sort($arr, $keys, $desc = false)
{
$key_value = $new_array = array();
foreach ($arr as $k => $v) {
$key_value[$k] = $v[$keys];
}
if ($desc) {
arsort($key_value);
} else {
asort($key_value);
}
reset($key_value);
foreach ($key_value as $k => $v) {
$new_array[$k] = $arr[$k];
}
return $new_array;
}
/**
* 数据导出到excel(csv文件)
* @param $fileName
* @param array $tileArray
* @param array $dataArray
*/
function export_excel($fileName, $tileArray = [], $dataArray = [])
{
ini_set('memory_limit', '512M');
ini_set('max_execution_time', 0);
ob_end_clean();
ob_start();
header("Content-Type: text/csv");
header("Content-Disposition:filename=" . $fileName);
$fp = fopen('php://output', 'w');
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
fputcsv($fp, $tileArray);
$index = 0;
foreach ($dataArray as $item) {
if ($index == 1000) {
$index = 0;
ob_flush();
flush();
}
$index++;
fputcsv($fp, $item);
}
ob_flush();
flush();
ob_end_clean();
}
/**
* 隐藏敏感字符
* @param $value
* @return string
*/
function substr_cut($value)
{
$strlen = mb_strlen($value, 'utf-8');
if ($strlen <= 1) return $value;
$firstStr = mb_substr($value, 0, 1, 'utf-8');
$lastStr = mb_substr($value, -1, 1, 'utf-8');
return $strlen == 2 ? $firstStr . str_repeat('*', $strlen - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}
/**
* 获取当前系统版本号
* @return mixed|null
* @throws Exception
*/
function get_version()
{
//return '1.0.1';
static $version = null;
if ($version) {
return $version;
}
$file = ROOT_PATH . '/version.json';
if (!file_exists($file)) {
throw new Exception('version.json not found');
}
$version = json_decode(file_get_contents($file), true);
if (!is_array($version)) {
throw new Exception('version cannot be decoded');
}
return $version['version'];
}
/**
* 获取全局唯一标识符
* @param bool $trim
* @return string
*/
function getGuidV4($trim = true)
{
// Windows
if (function_exists('com_create_guid') === true) {
$charid = com_create_guid();
return $trim == true ? trim($charid, '{}') : $charid;
}
// OSX/Linux
if (function_exists('openssl_random_pseudo_bytes') === true) {
$data = openssl_random_pseudo_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
// Fallback (PHP 4.2+)
mt_srand((double)microtime() * 10000);
$charid = strtolower(md5(uniqid(rand(), true)));
$hyphen = chr(45); // "-"
$lbrace = $trim ? "" : chr(123); // "{"
$rbrace = $trim ? "" : chr(125); // "}"
$guidv4 = $lbrace .
substr($charid, 0, 8) . $hyphen .
substr($charid, 8, 4) . $hyphen .
substr($charid, 12, 4) . $hyphen .
substr($charid, 16, 4) . $hyphen .
substr($charid, 20, 12) .
$rbrace;
return $guidv4;
}
function getRandMd5($start = 0, $len = 32)
{
return ($len == 16 ? 'hr' : '') . substr(md5(time() . mt_rand(1000, 9999) . 'hr'), $start, $len);
}
/**
* 时间戳转换日期
* @param $timeStamp
* @return false|string
*/
function format_time($timeStamp)
{
return date('Y-m-d H:i:s', $timeStamp);
}
/**
* 左侧填充0
* @param $value
* @param int $padLength
* @return string
*/
function pad_left($value, $padLength = 2)
{
return \str_pad($value, $padLength, "0", STR_PAD_LEFT);
}
/**
* 获取跳转的真实地址
* 如果访问链接是有跳转的,则获得真实跳转地址。
* public function index()
* {
* return get_redirect_url('http://api.tp5024.com/index.php?s=/oauth/token/a');
* }
* public function a() {
* return redirect('build123');
* }
*/
function get_redirect_url($url)
{
$redirect_url = null;
$url_parts = @parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false;
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
$request .= 'Host: ' . $url_parts['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($sock, $request);
$response = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)) {
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
/**
* 获取客户端IP地址
* @return mixed
*/
function getClientIp1()
{
$ip = false;
//客户端IP 或 NONE
if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
//多重代理服务器下的客户端真实IP地址(可能伪造),如果没有使用代理,此字段为空
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
if ($ip) {
array_unshift($ips, $ip);
$ip = false;
}
for ($i = 0; $i < count($ips); $i++) {
if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
$ip = $ips[$i];
break;
}
}
}
//客户端IP 或 (最后一个)代理服务器 IP
return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
/**
* 获取客户端IP地址
* @param integer $type
* 0 返回IP地址
* 1 返回IPV4地址数字
* @return mixed
*/
function getClientIp($type = 0) {
$type = $type ? 1 : 0;
$ip = null;
if ($ip !== null) return $ip[$type];
//nginx 代理模式下,获取客户端真实IP
if (isset($_SERVER['HTTP_X_REAL_IP'])) {
$ip = $_SERVER['HTTP_X_REAL_IP'];
}
// 客户端的ip
elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
// 浏览当前页面的用户计算机的网关
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown', $arr);
if (false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
//浏览当前页面的用户计算机的ip地址
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u", ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}