Frenlee

PHP中CURL类库封装

在PHP中很多时候需要去请求别人API的数据或者是用想其他服务器发送请求,以获取一些数据,通常比较简单的方法就是使用CURL这样一个类库,当然使用socket也是可行的,不过大多时候curl已经能够满足我们的需求,这里对CURL进行了简单的封装.主要是对curl进行了get和post方法的封装,支持多个请求同时进行.

实现

代码如下:

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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
<?php
/**
* 网络请求
* author: v_frli <frenlee@163.com>
* since: 2015/10/23 17:17
*/
class Http_Request{
public $url = false;//请求URL
public $method = 'GET';//请求方式信息
public $fields = null;//请求数据
public $headers = null;//头部信息
public $options = null;//curl选项

/**
* 构造函数
* @param $url
* @param string $method
* @param null $fields
* @param null $headers
* @param null $options
*/
function __construct($url, $method = 'GET', $fields = null, $headers = null, $options = null){
$this->url = $url;
$this->method = $method;
$this->fields = $fields;
$this->headers = $headers;
$this->options = $options;
}

/**
* 设置超时
* @param $timeout
*/
public function set_timeout($timeout){
$this->options[CURLOPT_TIMEOUT] = $timeout;
}

/**
* 设置代理
* @param $proxy
*/
public function set_proxy($proxy){
$this->options[CURLOPT_PROXY] = $proxy;
}

/**
* 设置referer
* @param $referer
*/
public function set_referer($referer){
$this->options[CURLOPT_REFERER] = $referer;
}

/**
* 设置 user_agent
*
* @param string $useragent
* @return void
*/
public function set_useragent($useragent)
{
$this->options[CURLOPT_USERAGENT] = $useragent;
}

/**
* 设置COOKIE
*
* @param string $cookie
* @return void
*/
public function set_cookie($cookie)
{
$this->options[CURLOPT_COOKIE] = $cookie;
}

/**
* 设置COOKIE JAR
*
* @param string $cookie_jar
* @return void
*/
public function set_cookiejar($cookiejar)
{
$this->options[CURLOPT_COOKIEJAR] = $cookiejar;
}

/**
* 设置COOKIE FILE
*
* @param string $cookie_file
* @return void
*/
public function set_cookiefile($cookiefile)
{
$this->options[CURLOPT_COOKIEFILE] = $cookiefile;
}

/**
* 设置IP
*
* @param string $ip
* @return void
*/
public function set_ip($ip)
{
$headers = array(
'CLIENT-IP'=>$ip,
'X-FORWARDED-FOR'=>$ip,
);
$this->headers = $this->headers + $headers;
}

/**
* 设置Headers
*
* @param string $headers
* @return void
*/
public function set_headers($headers)
{
$this->options[CURLOPT_TIMEOUT] = $headers;
}

/**
* 设置Hosts
*
* @param string $hosts
* @return void
*/
public function set_hosts($hosts)
{
$headers = array(
'Host'=>$hosts,
);
$this->headers = $this->headers + $headers;
}

/**
* 设置Gzip
*
* @param string $hosts
* @return void
*/
public function set_gzip($gzip)
{
if ($gzip)
{
$this->options[CURLOPT_ENCODING] = 'gzip';
}
}

/**
* 析构函数
*/
public function __destruct(){
unset($this->url,$this->method,$this->fields,$this->options);
}

}

/**
* 异常类
*/
class Http_Exception extends Exception {
}

class Http{

public $window_size = 5;//同时运行任务数
private $time_out = 10;//curl_multi_select 超时时间
public $callback;//回调函数
protected $options = array(
CURLOPT_SSL_VERIFYHOST => FALSE,//终止从服务端进行验证
CURLOPT_RETURNTRANSFER => TRUE,//以文本形式返回
CURLOPT_CONNECTTIMEOUT => 30,//连接超时
CURLOPT_TIMEOUT => 60,//请求超时
CURLOPT_HEADER => FALSE,//是否返回头部信息
// 在多线程处理场景下使用超时选项时,会忽略signals对应的处理函数,但是无耐的是还有小概率的crash情况发生
CURLOPT_NOSIGNAL => 1,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat",
);

private $headers = array();//头部信息
private $requsets = array();//请求队列
private $requestMap = array();//句柄与请求映射

function __construct($callback = null) {
$this->callback = $callback;
}

/**
* 获取成员变量
* @param $name
* @return null
*/
public function __get($name) {
return (isset($this->{$name})) ? $this->{$name} : null;
}

/**
* 设置成员变量
* @param $name
* @param $value
* @return bool
*/
public function __set($name, $value) {
if($name == 'options' || $name == 'headers'){
$this->{$name} = $value + $this->{$name};
} else {
$this->{$name} = $value;
}
return true;
}

/**
* 添加请求
* @param $request
* @return bool
*/
public function add($request){
$this->requsets[] = $request;
return true;
}

/**
* 添加请求
* @param $url
* @param string $method
* @param null $fields
* @param null $headers
* @param null $options
* @return bool
*/
public function request($url, $method = 'GET', $fields = null, $headers = null, $options = null ) {
$this->requsets[] = new Http_Request($url, $method, $fields, $headers, $options);
return true;
}

/**
* 添加一个GET请求
* @param $url
* @param null $fields
* @param null $headers
* @param null $options
* @return bool
*/
public function get($url, $fields= null, $headers = null , $options = null) {
return $this->request($url, 'GET', $fields, $headers, $options);
}

/**
* 添加一个POST请求
* @param $url
* @param null $fields
* @param null $headers
* @param null $options
* @return bool
*/
public function post($url, $fields = null, $headers = null, $options = null ) {
return $this->request($url, 'GET', $fields, $headers, $options);
}

/**
* 执行请求
* @param null $window_size
* @return mixed
*/
public function execute($window_size = null){
if(sizeof($this->requsets) == 1) {
return $this->single_curl();
} else {
return $this->multi_curl($window_size);
}
}

/**
* 单个请求
* @return bool|mixed|string
*/
public function single_curl(){
$ch = curl_init();
$request = array_shift($this->requsets);
$options = $this->get_options($request);
curl_setopt_array($ch, $options);
$output = curl_exec($ch);
$info = curl_getinfo($ch);


if($this->callback) {
$callback = $this->callback;
if(is_callable($this->callback)){
call_user_func($callback, $output, $info, $request);
}
} else return $output;
return true;
}

public function multi_curl($window_size = null ) {
if($window_size){
$this->window_size = $window_size;
}

//最大请求数大于实际请求数
if(sizeof($this->requsets) < $this->window_size) {
$this->window_size = sizeof($this->requsets);
}

if($this->window_size < 2){
throw new Http_Exception('请求数必须大于1');
}

$master = curl_multi_init();

for($i = 0;$i < $this->window_size; $i++) {
$ch = curl_init();
$options = $this->get_options($this->requsets[$i]);
curl_setopt_array($ch, $options);
curl_multi_add_handle($master, $ch);
$key = (string)$ch;
$this->requestMap[$key] = $i;
}

do{
while (($exec_run = curl_multi_exec($master, $running) == CURLM_CALL_MULTI_PERFORM));
if($exec_run != CURLM_OK)
break;
while ($done = curl_multi_info_read($master)) {
$info = curl_getinfo($done['handle']);
$output = curl_multi_getcontent($done['handle']);

$callback = $this->callback;
if(is_callable($callback)){
$key = (string)$done['handle'];
$request = $this->requsets[$this->requestMap[$key]];
unset($this->requestMap[$key]);
call_user_func($callback, $output, $info, $request);
}

if($i < sizeof($this->requsets) && isset($this->requsets[$i]) && $i < count($this->requsets)) {
$ch = curl_init();
$options = $this->get_options($this->requsets[$i]);
curl_setopt_array($ch, $options);
curl_multi_add_handle($master, $ch);
$key = (string)$ch;
$this->requestMap[$key] = $i;
$i++;
}
curl_multi_remove_handle($master, $done['handle']);
}

if($running){
curl_multi_select($master, $this->time_out);
}
} while($running);
curl_multi_close($master);
return true;
}

/**
* 分离头部信息和主体信息
* @param $output
* @param $info
*/
public function explode_headers($output, $info){
$header_size = $info[CURLINFO_HEADER_SIZE];
$headers = $this->parse_headers($output, 0, $header_size);
$output = substr($output, $header_size);
$ret['headers'] = isset($headers) ? $headers : FALSE;
$ret['output'] = $output;
}

private function get_options($request) {
//获取选项
$options = $this->__get('options');
if (ini_get('safe_mode') == 'Off' || !ini_get('safe_mode')) {
$options[CURLOPT_FOLLOWLOCATION] = 1;
$options[CURLOPT_MAXREDIRS] = 5;
}
$headers = $this->__get('headers');

//添加默认的选项
if ($request->options) {
$options = $request->options + $options;
}

//设置请求地址
$options[CURLOPT_URL] = $request->url;
if($request->fields) {
if($request->method == 'POST'){
$options[CURLOPT_POST] = 1;
$options[CURLOPT_POSTFIELDS] = $request->post_data;
}else{
$params = http_build_query($request->fields);
$options[CURLOPT_URL] .= (strpos($options[CURLOPT_URL], '?') ? '?' : '&') .$params;
}
}

if ($headers) {
$options[CURLOPT_HEADER] = 0;
$options[CURLOPT_HTTPHEADER] = $headers;
}

return $options;
}

/**
* @return void
*/
public function __destruct() {
unset($this->window_size, $this->callback, $this->options, $this->headers, $this->requests);
}


/**
* 头部信息转换
* @param $raw
* @return array
*/
private function parse_headers($raw)
{
$headers = array();
$header_lines = explode('\r\n', $raw);
foreach($header_lines as $line){
$header_line = trim($line);
$kv = explode(':', $header_line);
if(count($kv) > 1){
$headers[$kv[0]] = trim($kv[1]);
}
}
return $headers;
}


/*=====================设置请求选项公共信息*/
/**
* 设置超时
* @param $timeout
*/
public function set_timeout($timeout){
$this->options[CURLOPT_TIMEOUT] = $timeout;
}

/**
* 设置代理
* @param $proxy
*/
public function set_proxy($proxy){
$this->options[CURLOPT_PROXY] = $proxy;
}

/**
* 设置referer
* @param $referer
*/
public function set_referer($referer){
$this->options[CURLOPT_REFERER] = $referer;
}

/**
* 设置 user_agent
*
* @param string $useragent
* @return void
*/
public function set_useragent($useragent)
{
$this->options[CURLOPT_USERAGENT] = $useragent;
}

/**
* 设置COOKIE
*
* @param string $cookie
* @return void
*/
public function set_cookie($cookie)
{
$this->options[CURLOPT_COOKIE] = $cookie;
}

/**
* 设置COOKIE JAR
*
* @param string $cookie_jar
* @return void
*/
public function set_cookiejar($cookiejar)
{
$this->options[CURLOPT_COOKIEJAR] = $cookiejar;
}

/**
* 设置COOKIE FILE
*
* @param string $cookie_file
* @return void
*/
public function set_cookiefile($cookiefile)
{
$this->options[CURLOPT_COOKIEFILE] = $cookiefile;
}

/**
* 设置IP
*
* @param string $ip
* @return void
*/
public function set_ip($ip)
{
$headers = array(
'CLIENT-IP'=>$ip,
'X-FORWARDED-FOR'=>$ip,
);
$this->headers = $this->headers + $headers;
}

/**
* 设置Headers
*
* @param string $headers
* @return void
*/
public function set_headers($headers){
$this->options[CURLOPT_HEADER] = $headers;
}

/**
* 设置Hosts
*
* @param string $hosts
* @return void
*/
public function set_hosts($hosts){
$headers = array(
'Host'=>$hosts,
);
$this->headers = $this->headers + $headers;
}

/**
* 设置Gzip
*
* @param string $hosts
* @return void
*/
public function set_gzip($gzip){
if ($gzip) {
$this->options[CURLOPT_ENCODING] = 'gzip';
}
}

}

测试

测试函数如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
require_once 'Http.php';

function callback($output, $info, $request){
var_dump($output);
echo "<hr>";
var_dump($info);
echo "<hr>";
var_dump($request);
}
test();

function test(){
$url = 'http://www.baidu.com';
$http = new Http('callback');
$req = new Http_Request($url);
$http->add($req);
$http->execute();
}