-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcustomCurl.php
521 lines (493 loc) · 14.7 KB
/
customCurl.php
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
512
513
514
515
516
517
518
519
520
521
<?php
// +----------------------------------------------------------------------
// | Custom Curl
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://233.imjs.work All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://www.gnu.org/licenses/gpl-3.0.html )
// +----------------------------------------------------------------------
// | Author: jshensh <jshensh@126.com>
// +----------------------------------------------------------------------
/**
* Custom Curl 通用工具类
* @author jshensh <jshensh@126.com>
*/
class CustomCurlCommon
{
/**
* 解析 Cookie
* @access protected
* @param string $cookie Cookies 字符串
* @return array
*/
protected static function parseCookie($cookie)
{
$op = [];
$pieces = array_filter(array_map('trim', explode(';', $cookie)));
if (empty($pieces) || !strpos($pieces[0], '=')) {
return [];
}
foreach ($pieces as $part) {
$cookieParts = explode('=', $part, 2);
$key = trim($cookieParts[0]);
$value = isset($cookieParts[1])
? trim($cookieParts[1], " \n\r\t\0\x0B")
: true;
$op[$key] = $value;
}
return $op;
}
}
/**
* Custom Curl 结果类
* @author jshensh <jshensh@126.com>
*/
class CustomCurlStatement extends CustomCurlCommon
{
private $ch = null,
$output = '',
$body = '',
$header = '',
$responseCookies = [],
$curlInfo = [],
$curlErrNo = 0,
$status = false;
/**
* 构造方法
* @access public
* @param int $curlErrNo Curl 错误码
* @param resource $ch Curl 句柄
* @param string $output 请求结果
* @return void
*/
public function __construct($curlErrNo, $ch, $output) {
if ($curlErrNo !== 0) {
$this->curlErrNo = $curlErrNo;
return;
}
$this->status = true;
$this->curlInfo = curl_getinfo($ch);
$headerSize = $this->curlInfo['header_size'];
$this->header = substr($output, 0, $headerSize);
$this->body = substr($output, $headerSize);
preg_match_all('/Set-Cookie:(.*?)(\r\n|$)/is', $this->header, $responseCookiesArr);
if (count($responseCookiesArr[1])) {
foreach ($responseCookiesArr[1] as $value) {
$this->responseCookies[] = self::parseCookie($value);
}
}
}
/**
* 获取请求结果状态
* @access public
* @return bool
*/
public function getStatus()
{
return $this->status;
}
/**
* 获取请求结果的 body 部分
* @access public
* @return string
*/
public function getBody()
{
return $this->body;
}
/**
* 获取请求结果的 Header 部分
* @access public
* @return string
*/
public function getHeader()
{
return $this->header;
}
/**
* 获取 Curl 错误码
* @access public
* @return int
*/
public function getCurlErrNo()
{
return $this->curlErrNo;
}
/**
* 获取请求结果的 Cookies 数组
* @access public
* @return array
*/
public function getCookies()
{
return $this->responseCookies;
}
/**
* 获取请求结果的 Info
* @access public
* @param string $key Curl Info Key
* @return mixed
*/
public function getInfo($key = '')
{
return $key ? (isset($this->curlInfo[$key]) ? $this->curlInfo[$key] : false) : $this->curlInfo;
}
}
/**
* Custom Curl 类
* @author jshensh <jshensh@126.com>
*/
class CustomCurl extends CustomCurlCommon
{
private static $defaultConf = [
'timeout' => 5,
'reRequest' => 3,
'maxRedirs' => 3,
'ignoreCurlError' => false,
'followLocation' => false,
'referer' => '',
'userAgent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36',
'customHeader' => [],
'sendCookies' => [],
'autoRefer' => 1,
'postType' => 'form',
'proxy' => '',
'proxyPort' => 8080,
'proxyUserPwd' => '',
'proxyType' => CURLPROXY_HTTP
],
$defaultCurlopt = [
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_ENCODING => ''
],
$userConf = [],
$userCurlopt = [];
private $url = '',
$method = '',
$conf = [
'postFields' => []
],
$curlopt = [];
/**
* 构造方法
* @access private
* @param string $url URL 字符串
* @param string $method 请求方法,[get, post, put, delete]
* @return void
*/
private function __construct($url, $method)
{
$this->url = $url;
$method = strtolower($method);
$this->conf = array_merge(self::$defaultConf, self::$userConf);
$this->curlopt = self::$defaultCurlopt;
foreach (self::$userCurlopt as $key => $value) {
$this->curlopt[$key] = $value;
}
$this->method = in_array($method, ['get', 'post', 'put', 'delete']) ? $method : 'get';
}
/**
* 设置默认配置
* @access public
* @param string $k 配置 Key
* @param string $v 配置 Value
* @return bool
*/
public static function setConf($k, $v)
{
if (!isset(self::$defaultConf[$k])) {
return false;
}
if ($k === 'sendCookies') {
if (is_string($v)) {
$v = self::parseCookie($v);
}
if (is_array($v)) {
if (count($v) !== count($v, 1)) {
return false;
}
} else {
return false;
}
}
self::$userConf[$k] = $v;
return true;
}
/**
* 恢复默认配置
* @access public
* @param string $k 配置 Key
* @return bool
*/
public static function resetConf($k = null)
{
if ($k) {
if (!isset(self::$userConf[$k])) {
return false;
}
unset(self::$userConf[$k]);
return true;
}
self::$userConf = [];
return true;
}
/**
* 设置默认 CurlOpt
* @access public
* @param string $k 配置 Key
* @param string $v 配置 Value
* @return bool
*/
public static function setCurlOptConf($k, $v)
{
if (!isset(self::$defaultCurlopt[$k])) {
return false;
}
self::$userCurlopt[$k] = $v;
return true;
}
/**
* 恢复默认 CurlOpt
* @access public
* @param string $k 配置 Key
* @return bool
*/
public static function resetCurlOptConf($k = null)
{
if ($k) {
if (!isset(self::$userCurlopt[$k])) {
return false;
}
unset(self::$userCurlopt[$k]);
return true;
}
self::$userCurlopt = [];
return true;
}
/**
* 初始化
* @access public
* @param string $url URL 字符串
* @param string $method 请求方法,post 或者 get
* @return CustomCurl
*/
public static function init($url, $method = 'get')
{
return new self($url, $method);
}
/**
* 设置项
* @access public
* @param string $k 设置项 Key
* @param string $v 设置项 Value
* @return CustomCurl
*/
public function set($k, $v)
{
switch ($k) {
case 'timeout':
// no break
case 'maxRedirs':
// no break
case 'reRequest':
if ($v < 0 || !is_numeric($v)) {
return $this;
}
break;
case 'postFields':
if (!in_array($this->method, ['post', 'put'])) {
return $this;
}
break;
case 'postType':
$v = strtolower($v);
if (!in_array($v, ['string', 'form', 'json'])) {
return $this;
}
break;
case 'ignoreCurlError':
// no break
case 'followLocation':
// no break
case 'autoRefer':
$v = (bool)$v;
break;
case 'referer':
// no break
case 'proxy':
// no break
case 'proxyPort':
// no break
case 'proxyUserPwd':
// no break
case 'proxyType':
// no break
case 'userAgent':
break;
default:
return $this;
}
$this->conf[$k] = $v;
return $this;
}
/**
* 设置 CurlOpt
* @access public
* @param string $k 设置项 Key
* @param string $v 设置项 Value
* @return CustomCurl
*/
public function setCurlOpt($k, $v)
{
switch ($k) {
case CURLOPT_SSL_VERIFYPEER:
// no break
case CURLOPT_SSL_VERIFYHOST:
if (!is_bool($v)) {
return $this;
}
case CURLOPT_ENCODING:
if (!is_string($v)) {
return $this;
}
break;
default:
return $this;
}
$this->curlopt[$k] = $v;
return $this;
}
/**
* 设置 Header
* @access public
* @param string $k Header Key
* @param string $v Header Value
* @return CustomCurl
*/
public function setHeader($k, $v)
{
$this->conf['customHeader'][] = "{$k}: {$v}";
return $this;
}
/**
* 清空设置的 Header
* @access public
* @return CustomCurl
*/
public function clearHeaders()
{
$this->conf['customHeader'] = [];
return $this;
}
/**
* 设置 Cookie
* @access public
* @param string $k Cookie Key
* @param string $v Cookie Value
* @return CustomCurl
*/
public function setCookie($k, $v)
{
$this->conf['sendCookies'][$k] = $v;
return $this;
}
/**
* 设置 Cookies
* @access public
* @param string|array $parm Cookies 字符串或一维数组
* @param bool $append 是否追加设置
* @return CustomCurl
*/
public function setCookies($parm, $append = false)
{
$cookies = is_array($parm) ? $parm : self::parseCookie($parm);
$cookiesC = count($cookies);
if (!$cookiesC || ($cookiesC !== count($cookies, 1))) {
return $this;
}
if ($append) {
$this->conf['sendCookies'] = array_merge($this->conf['sendCookies'], $cookies);
} else {
$this->conf['sendCookies'] = $cookies;
}
return $this;
}
/**
* 清空 Cookies
* @access public
* @return CustomCurl
*/
public function clearCookies()
{
$this->conf['sendCookies'] = [];
return $this;
}
/**
* 执行 Curl
* @access public
* @return CustomCurlStatement
*/
public function exec()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->conf['timeout']);
curl_setopt($ch, CURLOPT_REFERER, $this->conf['referer']);
curl_setopt($ch, CURLOPT_USERAGENT, $this->conf['userAgent']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $this->conf['followLocation']);
curl_setopt($ch, CURLOPT_MAXREDIRS, $this->conf['maxRedirs']);
curl_setopt($ch, CURLOPT_AUTOREFERER, $this->conf['autoRefer']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($this->method));
if (count($this->conf['sendCookies'])) {
$sendCookies = '';
foreach ($this->conf['sendCookies'] as $key => $value) {
$sendCookies .= "{$key}={$value}; ";
}
curl_setopt($ch, CURLOPT_COOKIE, $sendCookies);
}
if (in_array($this->method, ['post', 'put'])) {
if ($this->conf['postType'] === 'json') {
$postJsonData = json_encode($this->conf['postFields']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postJsonData);
$this->conf['customHeader'][] = 'Content-Type: application/json';
$this->conf['customHeader'][] = 'Content-Length: ' . strlen($postJsonData);
} else if ($this->conf['postType'] === 'form') {
if (is_array($this->conf['postFields'])) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($this->conf['postFields']));
}
} else {
if (is_string($this->conf['postFields'])) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->conf['postFields']);
$this->conf['customHeader'][] = 'Content-Type: text/plain';
$this->conf['customHeader'][] = 'Content-Length: ' . strlen($this->conf['postFields']);
}
}
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->conf['customHeader']);
if ($this->conf['proxy']) {
curl_setopt($ch, CURLOPT_PROXY, $this->conf['proxy']);
curl_setopt($ch, CURLOPT_PROXYPORT, $this->conf['proxyPort']);
if ($this->conf['proxyUserPwd']) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->conf['proxyUserPwd']);
}
curl_setopt($ch, CURLOPT_PROXYTYPE, $this->conf['proxyType']);
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
foreach ($this->curlopt as $key => $value) {
curl_setopt($ch, $key, $value);
}
$output = curl_exec($ch);
$curlErrNo = curl_errno($ch);
if ($curlErrNo === 0 || ($this->conf['ignoreCurlError'] && $output)) {
return new CustomCurlStatement(0, $ch, $output);
}
$this->conf['reRequest']--;
if ($this->conf['reRequest'] > 0) {
return $this->exec();
}
return new CustomCurlStatement($curlErrNo, $ch, $output);
}
}