forked from jsocol/oocurl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOOCurl.php
558 lines (509 loc) · 13.2 KB
/
OOCurl.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
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
554
555
556
557
558
<?php
/**
* OOCurl
*
* Provides an Object-Oriented interface to the PHP cURL
* functions and clean up some of the curl_setopt() calls.
*
* @package OOCurl
* @author James Socol <[email protected]>
* @version 0.3.0
* @copyright Copyright (c) 2008-2013, James Socol
* @license See LICENSE
*/
/**
* Curl connection object
*
* Provides an Object-Oriented interface to the PHP cURL
* functions and a clean way to replace curl_setopt().
*
* Instead of requiring a setopt() function and the CURLOPT_*
* constants, which are cumbersome and ugly at best, this object
* implements curl_setopt() through overloaded getter and setter
* methods.
*
* For example, if you wanted to include the headers in the output,
* the old way would be
*
* <code>
* curl_setopt($ch, CURLOPT_HEADER, true);
* </code>
*
* But with this object, it's simply
*
* <code>
* $ch->header = true;
* </code>
*
* <b>NB:</b> Since, in my experience, the vast majority
* of cURL scripts set CURLOPT_RETURNTRANSFER to true, the {@link Curl}
* class sets it by default. If you do not want CURLOPT_RETURNTRANSFER,
* you'll need to do this:
*
* <code>
* $c = new Curl;
* $c->returntransfer = false;
* </code>
*
* @package OOCurl
* @author James Socol <[email protected]>
* @version 0.3.0
*/
class Curl
{
/**
* Store the curl_init() resource.
* @var resource
*/
protected $ch = NULL;
/**
* Store the CURLOPT_* values.
*
* Do not access directly. Access is through {@link __get()}
* and {@link __set()} magic methods.
*
* @var array
*/
protected $curlopt = array();
/**
* Flag the Curl object as linked to a {@link CurlParallel}
* object.
*
* @var bool
*/
protected $multi = false;
/**
* Store the response. Used with {@link fetch()} and
* {@link fetch_json()}.
*
* @var string
*/
protected $response;
/**
* The version of the OOCurl library.
* @var string
*/
const VERSION = '0.3';
/**
* Create the new {@link Curl} object, with the
* optional URL parameter.
*
* @param string $url The URL to open (optional)
* @return Curl A new Curl object.
* @throws ErrorException
*/
public function __construct ( $url = NULL )
{
// Make sure the cURL extension is loaded
if ( !extension_loaded('curl') )
throw new ErrorException("cURL library is not loaded. Please recompile PHP with the cURL library.");
// Create the cURL resource
$this->ch = curl_init();
// Set some default options
$this->url = $url;
$this->returntransfer = true;
// Applications can override this User Agent value
$this->useragent = 'OOCurl '.self::VERSION;
// Return $this for chaining
return $this;
}
/**
* When destroying the object, be sure to free resources.
*/
public function __destruct()
{
$this->close();
}
/**
* If the session was closed with {@link Curl::close()}, it can be reopened.
*
* This does not re-execute {@link Curl::__construct()}, but will reset all
* the values in {@link $curlopt}.
*
* @param string $url The URL to open (optional)
* @return bool|Curl
*/
public function init ( $url = NULL )
{
// If it's still init'ed, return false.
if ( $this->ch ) return false;
// init a new cURL session
$this->ch = curl_init();
// reset all the values that were already set
foreach ( $this->curlopt as $const => $value ) {
curl_setopt($this->ch, constant($const), $value);
}
// finally if there's a new URL, set that
if ( !empty($url) ) $this->url = $url;
// return $this for chaining
return $this;
}
/**
* Execute the cURL transfer.
*
* @return mixed
*/
public function exec ()
{
return curl_exec($this->ch);
}
/**
* If the Curl object was added to a {@link CurlParallel}
* object, then you can use this function to get the
* returned data (whatever that is). Otherwise it's similar
* to {@link exec()} except it saves the output, instead of
* running the request repeatedly.
*
* @see $multi
* @return mixed
*/
public function fetch ()
{
if ( $this->multi ) {
return curl_multi_getcontent($this->ch);
} else {
if ( $this->response ) {
return $this->response;
} else {
$this->response = curl_exec($this->ch);
return $this->response;
}
}
}
/**
* Fetch a JSON encoded value and return a JSON
* object. Requires the PHP JSON functions. Pass TRUE
* to return an associative array instead of an object.
*
* @param bool array optional. Return an array instead of an object.
* @return mixed an array or object (possibly null).
*/
public function fetch_json ( $array = false )
{
return json_decode($this->fetch(), $array);
}
/**
* Close the cURL session and free the resource.
*/
public function close ()
{
if ( !empty($this->ch) && is_resource($this->ch) )
curl_close($this->ch);
}
/**
* Return an error string from the last execute (if any).
*
* @return string
*/
public function error()
{
return curl_error($this->ch);
}
/**
* Return the error number from the last execute (if any).
*
* @return integer
*/
public function errno()
{
return curl_errno($this->ch);
}
/**
* Get cURL version information (and adds OOCurl version info)
*
* @return array
*/
public function version ()
{
$version = curl_version();
$version['oocurl_version'] = self::VERSION;
$version['oocurlparallel_version'] = CurlParallel::VERSION;
return $version;
}
/**
* Get information about this transfer.
*
* Accepts any of the following as a parameter:
* - Nothing, and returns an array of all info values
* - A CURLINFO_* constant, and returns a string
* - A string of the second half of a CURLINFO_* constant,
* for example, the string 'effective_url' is equivalent
* to the CURLINFO_EFFECTIVE_URL constant. Not case
* sensitive.
*
* @param mixed $opt A string or constant (optional).
* @return mixed An array or string.
*/
public function info ( $opt = false )
{
if (false === $opt) {
return curl_getinfo($this->ch);
}
if ( is_int($opt) || ctype_digit($opt) ) {
return curl_getinfo($this->ch,$opt);
}
if (constant('CURLINFO_'.strtoupper($opt))) {
return curl_getinfo($this->ch,constant('CURLINFO_'.strtoupper($opt)));
}
}
/**
* Magic property setter.
*
* A sneaky way to access curl_setopt(). If the
* constant CURLOPT_$opt exists, then we try to set
* the option using curl_setopt() and return its
* success. If it doesn't exist, just return false.
*
* Also stores the variable in {@link $curlopt} so
* its value can be retrieved with {@link __get()}.
*
* @param string $opt The second half of the CURLOPT_* constant, not case sensitive
* @param mixed $value
* @return void
*/
public function __set ( $opt, $value )
{
$const = 'CURLOPT_'.strtoupper($opt);
if ( defined($const) ) {
if (curl_setopt($this->ch,
constant($const),
$value)) {
$this->curlopt[$const] = $value;
}
}
}
/**
* Magic property getter.
*
* When options are set with {@link __set()}, they
* are also stored in {@link $curlopt} so that we
* can always find out what the options are now.
*
* The default cURL functions lack this ability.
*
* @param string $opt The second half of the CURLOPT_* constant, not case sensitive
* @return mixed The set value of CURLOPT_<var>$opt</var>, or NULL if it hasn't been set (ie: is still default).
*/
public function __get ( $opt )
{
return $this->curlopt['CURLOPT_'.strtoupper($opt)];
}
/**
* Magic property isset()
*
* Can tell if a CURLOPT_* value was set by using
* <code>
* isset($curl->*)
* </code>
*
* The default cURL functions lack this ability.
*
* @param string $opt The second half of the CURLOPT_* constant, not case sensitive
* @return bool
*/
public function __isset ( $opt )
{
return isset($this->curlopt['CURLOPT_'.strtoupper($opt)]);
}
/**
* Magic property unset()
*
* Unfortunately, there is no way, short of writing an
* extremely long, but mostly NULL-filled array, to
* implement a decent version of
* <code>
* unset($curl->option);
* </code>
*
* @todo Consider implementing an array of all the CURLOPT_*
* constants and their default values.
* @param string $opt The second half of the CURLOPT_* constant, not case sensitive
* @return void
*/
public function __unset ( $opt )
{
// Since we really can't reset a CURLOPT_* to its
// default value without knowing the default value,
// just do nothing.
}
/**
* Grants access to {@link Curl::$ch $ch} to a {@link CurlParallel} object.
*
* @param CurlParallel $mh The CurlParallel object that needs {@link Curl::$ch $ch}.
*/
public function grant ( CurlParallel $mh )
{
$mh->accept($this->ch);
$this->multi = true;
}
/**
* Removes access to {@link Curl::$ch $ch} from a {@link CurlParallel} object.
*
* @param CurlParallel $mh The CurlParallel object that no longer needs {@link Curl::$ch $ch}.
*/
public function revoke ( CurlParallel $mh )
{
$mh->release($this->ch);
$this->multi = false;
}
}
/**
* Implements parallel-processing for cURL requests.
*
* The PHP cURL library allows two or more requests to run in
* parallel (at the same time). If you have multiple requests
* that may have high latency but can then be processed quickly
* in series (one after the other), then running them at the
* same time may save time, overall.
*
* You must create individual {@link Curl} objects first, add them to
* the CurlParallel object, execute the CurlParallel object,
* then get the data from the individual {@link Curl} objects. (Yes,
* it's annoying, but it's limited by the PHP cURL library.)
*
* For example:
*
* <code>
* $a = new Curl("http://www.yahoo.com/");
* $b = new Curl("http://www.microsoft.com/");
*
* $m = new CurlParallel($a, $b);
*
* $m->exec(); // Now we play the waiting game.
*
* printf("Yahoo is %n characters.\n", strlen($a->fetch()));
* printf("Microsoft is %n characters.\n", strlen($a->fetch()));
* </code>
*
* You can add any number of {@link Curl} objects to the
* CurlParallel object's constructor (including 0), or you
* can add with the {@link add()} method:
*
* <code>
* $m = new CurlParallel;
*
* $a = new Curl("http://www.yahoo.com/");
* $b = new Curl("http://www.microsoft.com/");
*
* $m->add($a);
* $m->add($b);
*
* $m->exec(); // Now we play the waiting game.
*
* printf("Yahoo is %n characters.\n", strlen($a->fetch()));
* printf("Microsoft is %n characters.\n", strlen($a->fetch()));
* </code>
*
* @package OOCurl
* @author James Socol <[email protected]>
* @version 0.3.0
* @since 0.1.2
*/
class CurlParallel
{
/**
* Store the cURL master resource.
* @var resource
*/
protected $mh;
/**
* Store the resource handles that were
* added to the session.
* @var array
*/
protected $ch = array();
/**
* Store the version number of this class.
*/
const VERSION = '0.3.0';
/**
* Initialize the multisession handler.
*
* @uses add()
* @param Curl $curl,... {@link Curl} objects to add to the Parallelizer.
* @return CurlParallel
*/
public function __construct ()
{
$this->mh = curl_multi_init();
foreach ( func_get_args() as $ch ) {
$this->add($ch);
}
return $this;
}
/**
* On destruction, frees resources.
*/
public function __destruct ()
{
$this->close();
}
/**
* Close the current session and free resources.
*/
public function close ()
{
foreach ( $this->ch as $ch ) {
curl_multi_remove_handle($this->mh, $ch);
}
curl_multi_close($this->mh);
}
/**
* Add a {@link Curl} object to the Parallelizer.
*
* Will throw a catchable fatal error if passed a non-Curl object.
*
* @uses Curl::grant()
* @uses CurlParallel::accept()
* @param Curl $ch Curl object.
*/
public function add ( Curl $ch )
{
// get the protected resource
$ch->grant($this);
}
/**
* Remove a {@link Curl} object from the Parallelizer.
*
* @param Curl $ch Curl object.
* @uses Curl::revoke()
* @uses CurlParallel::release()
*/
public function remove ( Curl $ch )
{
$ch->revoke($this);
}
/**
* Execute the parallel cURL requests.
*/
public function exec ()
{
do {
curl_multi_exec($this->mh, $running);
} while ($running > 0);
}
/**
* Accept a resource handle from a {@link Curl} object and
* add it to the master.
*
* @param resource $ch A resource returned by curl_init().
*/
public function accept ( $ch )
{
$this->ch[] = $ch;
curl_multi_add_handle($this->mh, $ch);
}
/**
* Accept a resource handle from a {@link Curl} object and
* remove it from the master.
*
* @param resource $ch A resource returned by curl_init().
*/
public function release ( $ch )
{
if ( false !== $key = array_search($this->ch, $ch) ) {
unset($this->ch[$key]);
curl_multi_remove_handle($this->mh, $ch);
}
}
}