forked from stefangabos/Zebra_cURL
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathZebra_cURL.php
More file actions
2258 lines (1986 loc) · 106 KB
/
Zebra_cURL.php
File metadata and controls
2258 lines (1986 loc) · 106 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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Zebra_cURL, a high performance PHP cURL library
*
* Zebra_cURL is a high performance PHP library acting as a wrapper to PHP's {@link http://www.php.net/manual/en/book.curl.php libcurl library},
* which not only allows the running of multiple requests at once asynchronously, in parallel, but also as soon as one
* thread finishes it can be processed right away without having to wait for the other threads in the queue to finish.
*
* Also, each time a request is completed another one is added to the queue, thus keeping a constant number of threads
* running at all times and eliminating wasted CPU cycles from busy waiting. This result is a faster and more efficient
* way of processing large quantities of cURL requests (like fetching thousands of RSS feeds at once), drastically reducing
* processing time.
*
* This script supports GET and POST request, basic downloads, downloads from FTP servers, HTTP Authentication, and
* requests through proxy servers.
*
* For maximum efficiency downloads are streamed (bytes downloaded are directly written to disk) removing the unnecessary
* strain from the server of having to read files into memory first, and then writing them to disk.
*
* Zebra_cURL requires the {@link http://www.php.net/manual/en/curl.installation.php PHP cURL extension} to be enabled.
*
* The code is heavily commented and generates no warnings/errors/notices when PHP's error reporting level is set to
* {@link http://www.php.net/manual/en/function.error-reporting.php E_ALL}.
*
* Visit {@link http://stefangabos.ro/php-libraries/zebra-curl/} for more information.
*
* For more resources visit {@link http://stefangabos.ro/}
*
* @author Stefan Gabos <contact@stefangabos.ro>
* @version 1.3.1 (last revision: February 03, 2015)
* @copyright (c) 2014 - 2015 Stefan Gabos
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE
* @package Zebra_cURL
*/
class Zebra_cURL {
/**
* The number of seconds to wait between processing batches of requests.
*
* If the value of this property is greater than 0, the library will process as many requests as defined by the
* {@link $threads threads} property, and then wait for {@link $pause_interval pause_interval} seconds before
* processing the next batch of requests.
*
* Default is 0 (the library will keep as many parallel threads as defined by {@link $threads threads} <b>running
* at all times</b>, until there are no more requests to process).
*
* @since 1.3.0
*
* @var integer
*/
public $pause_interval;
/**
* The number of parallel, asynchronous, requests to be processed by the library, at all times.
*
* <code>
* // process 30 simultaneous requests, at all times
* $curl->threads = 30;
* </code>
*
* Note that, unless {@link $pause_interval pause_interval} is set to a value greater than 0, the library will process
* a constant number of requests, <b>at all times</b>; it's doing this by processing a new request as soon as another
* one finishes, instead of waiting for each batch to finish, and so on, until there are no more requests to process,
* and thus greatly decreasing execution time.
*
* If {@link $pause_interval pause_interval} is set to a value greater than 0, the library will process as many
* requests as set by the {@link $threads threads} property and then will wait for {@link $pause_interval pause_interval}
* seconds before processing the next batch of requests.
*
* Default is 10.
*
* @var integer
*/
public $threads;
/**
* Used by the {@link _process()} method to determine whether to run processed requests' bodies through PHP's
* htmlentities function.
*
* Default is TRUE. Can be changed by instantiating the library with the FALSE argument.
*
* @access private
*
*/
private $_htmlentities;
/**
* Used to tell the library whether to queue requests or to process them right away
*
* @var resource
*
* @access private
*/
private $_queue;
/**
* The cURL multi handle
*
* @var resource
*
* @access private
*/
private $_multi_handle;
/**
* Used to keep track of all the requests that need to be processed.
*
* @access private
*/
private $_requests;
/**
* An associative array linked with all the resources, used to store original URL and file pointer resources, used
* for streaming downloads.
*
* @var array
*
* @access private
*/
private $_running;
/**
* Possible values of the "result" attribute in the object passed to the callback function.
*
* @var array
*
* @access private
*/
private $_response_messages = array(
0 => 'CURLE_OK',
1 => 'CURLE_UNSUPPORTED_PROTOCOL',
2 => 'CURLE_FAILED_INIT',
3 => 'CURLE_URL_MALFORMAT',
4 => 'CURLE_URL_MALFORMAT_USER',
5 => 'CURLE_COULDNT_RESOLVE_PROXY',
6 => 'CURLE_COULDNT_RESOLVE_HOST',
7 => 'CURLE_COULDNT_CONNECT',
8 => 'CURLE_FTP_WEIRD_SERVER_REPLY',
9 => 'CURLE_REMOTE_ACCESS_DENIED',
11 => 'CURLE_FTP_WEIRD_PASS_REPLY',
13 => 'CURLE_FTP_WEIRD_PASV_REPLY',
14 => 'CURLE_FTP_WEIRD_227_FORMAT',
15 => 'CURLE_FTP_CANT_GET_HOST',
17 => 'CURLE_FTP_COULDNT_SET_TYPE',
18 => 'CURLE_PARTIAL_FILE',
19 => 'CURLE_FTP_COULDNT_RETR_FILE',
21 => 'CURLE_QUOTE_ERROR',
22 => 'CURLE_HTTP_RETURNED_ERROR',
23 => 'CURLE_WRITE_ERROR',
25 => 'CURLE_UPLOAD_FAILED',
26 => 'CURLE_READ_ERROR',
27 => 'CURLE_OUT_OF_MEMORY',
28 => 'CURLE_OPERATION_TIMEDOUT',
30 => 'CURLE_FTP_PORT_FAILED',
31 => 'CURLE_FTP_COULDNT_USE_REST',
33 => 'CURLE_RANGE_ERROR',
34 => 'CURLE_HTTP_POST_ERROR',
35 => 'CURLE_SSL_CONNECT_ERROR',
36 => 'CURLE_BAD_DOWNLOAD_RESUME',
37 => 'CURLE_FILE_COULDNT_READ_FILE',
38 => 'CURLE_LDAP_CANNOT_BIND',
39 => 'CURLE_LDAP_SEARCH_FAILED',
41 => 'CURLE_FUNCTION_NOT_FOUND',
42 => 'CURLE_ABORTED_BY_CALLBACK',
43 => 'CURLE_BAD_FUNCTION_ARGUMENT',
45 => 'CURLE_INTERFACE_FAILED',
47 => 'CURLE_TOO_MANY_REDIRECTS',
48 => 'CURLE_UNKNOWN_TELNET_OPTION',
49 => 'CURLE_TELNET_OPTION_SYNTAX',
51 => 'CURLE_PEER_FAILED_VERIFICATION',
52 => 'CURLE_GOT_NOTHING',
53 => 'CURLE_SSL_ENGINE_NOTFOUND',
54 => 'CURLE_SSL_ENGINE_SETFAILED',
55 => 'CURLE_SEND_ERROR',
56 => 'CURLE_RECV_ERROR',
58 => 'CURLE_SSL_CERTPROBLEM',
59 => 'CURLE_SSL_CIPHER',
60 => 'CURLE_SSL_CACERT',
61 => 'CURLE_BAD_CONTENT_ENCODING',
62 => 'CURLE_LDAP_INVALID_URL',
63 => 'CURLE_FILESIZE_EXCEEDED',
64 => 'CURLE_USE_SSL_FAILED',
65 => 'CURLE_SEND_FAIL_REWIND',
66 => 'CURLE_SSL_ENGINE_INITFAILED',
67 => 'CURLE_LOGIN_DENIED',
68 => 'CURLE_TFTP_NOTFOUND',
69 => 'CURLE_TFTP_PERM',
70 => 'CURLE_REMOTE_DISK_FULL',
71 => 'CURLE_TFTP_ILLEGAL',
72 => 'CURLE_TFTP_UNKNOWNID',
73 => 'CURLE_REMOTE_FILE_EXISTS',
74 => 'CURLE_TFTP_NOSUCHUSER',
75 => 'CURLE_CONV_FAILED',
76 => 'CURLE_CONV_REQD',
77 => 'CURLE_SSL_CACERT_BADFILE',
78 => 'CURLE_REMOTE_FILE_NOT_FOUND',
79 => 'CURLE_SSH',
80 => 'CURLE_SSL_SHUTDOWN_FAILED',
81 => 'CURLE_AGAIN',
82 => 'CURLE_SSL_CRL_BADFILE',
83 => 'CURLE_SSL_ISSUER_ERROR',
84 => 'CURLE_FTP_PRET_FAILED',
85 => 'CURLE_RTSP_CSEQ_ERROR',
86 => 'CURLE_RTSP_SESSION_ERROR',
87 => 'CURLE_FTP_BAD_FILE_LIST',
88 => 'CURLE_CHUNK_FAILED',
);
/**
* Constructor of the class.
*
* Below is the list of default options set by the library when instantiated:
*
* - <b>CURLINFO_HEADER_OUT</b> - <b>TRUE</b>; get the last request header; if set to FALSE the "last_request"
* entry of the "headers" attribute of the object given as argument to the
* callback function, will be an empty string;
*
* - <b>CURLOPT_AUTOREFERER</b> - <b>TRUE</b>; automatically set the <i>Referer:</i> field in requests
* where it follows a <i>Location:</i> redirect;
*
* - <b>CURLOPT_COOKIEFILE</b> - <b>empty string</b>; no cookies are loaded, but cookie handling is still
* enabled
*
* - <b>CURLOPT_CONNECTTIMEOUT</b> - <b>10</b>; the number of seconds to wait while trying to connect. use 0
* to wait indefinitely;
*
* - <b>CURLOPT_ENCODING</b> - <b>gzip,deflate</b>; the contents of the "Accept-Encoding:" header; it
* enables decoding of the response
*
* - <b>CURLOPT_FOLLOWLOCATION</b> - <b>TRUE</b>; automatically follow any <i>Location:</i> header that the
* server sends as part of the HTTP header (note this is recursive, PHP will
* follow as many <i>Location:</i> headers as specified by the value of
* CURLOPT_MAXREDIRS - see below);
*
* - <b>CURLOPT_HEADER</b> - <b>TRUE</b>; get the response header(s); if set to FALSE the "responses"
* entry of the "headers" attribute of the object given as argument to the
* callback function, will be an empty string;
*
* - <b>CURLOPT_MAXREDIRS</b> - <b>50</b>; the maximum amount of HTTP redirections to follow; used
* together with CURLOPT_FOLLOWLOCATION;
*
* - <b>CURLOPT_RETURNTRANSFER</b> - <b>TRUE</b>; return the transfer's body as a string instead of outputting
* it directly; if set to FALSE the "body" attribute of the object given as
* argument to a callback function will be an empty string;
*
* - <b>CURLOPT_SSL_VERIFYHOST</b> - <b>2</b>; check the existence of a common name in the SSL peer certificate
* (for when connecting to HTTPS), and that it matches with the provided
* hostname; see also {@link ssl()};
*
* - <b>CURLOPT_SSL_VERIFYPEER</b> - <b>FALSE</b>; stop cURL from verifying the peer's certificate (which
* would most likely cause the request to fail). see also {@link ssl()};
*
* - <b>CURLOPT_TIMEOUT</b> - <b>10</b>; the maximum number of seconds to allow cURL functions to
* execute;
*
* - <b>CURLOPT_USERAGENT</b> - A (slightly) random user agent (Internet Explorer 9 or 10, on Windows
* Vista, 7 or 8, with other extra strings). Some web services will not
* respond unless a valid user-agent string is provided
*
* @param boolean $htmlentities Instructs the script whether the response body returned by the {@link get()}
* and {@link post()} methods should be run through PHP's
* {@link http://php.net/manual/en/function.htmlentities.php htmlentities()}
* function.
*
* @return void
*/
function __construct($htmlentities = true)
{
// if the cURL extension is not available, trigger an error and stop execution
if (!extension_loaded('curl')) trigger_error('php_curl extension is not loaded', E_USER_ERROR);
// initialize some private properties
$this->_multi_handle = $this->_queue = false;
$this->_running = $this->_requests = array();
// the default number of seconds to wait between processing batches of requests
// 0 means no waiting, process all requests at once
$this->pause_interval = 0;
// the default number of parallel, asynchronous, requests to be processed by the library at all times
// (unless the "pause_interval" property is greater than 0, case in which it refers to the number of requests
// to be processed before pausing)
$this->threads = 10;
// set the user's preference on whether to run htmlentities() on the response body or not
$this->_htmlentities = $htmlentities;
// set defaults for libcurl
// set defaults
$this->option(array(
// include the last request headers as a property of the object given as argument to the callback
CURLINFO_HEADER_OUT => 1,
// automatically set the "Referer:" field where it follows a "Location:" redirect
CURLOPT_AUTOREFERER => 1,
// the name of the file containing the cookie data; if the name is an empty string, no cookies are
// loaded, but cookie handling is still enabled
CURLOPT_COOKIEFILE => '',
// the number of seconds to wait while trying to connect
CURLOPT_CONNECTTIMEOUT => 10,
// the contents of the "Accept-Encoding:" header; it enables decoding of the response
CURLOPT_ENCODING => 'gzip,deflate',
// follow any "Location:" header that the server sends as part of the HTTP header - note this is recursive
// and that PHP will follow as many "Location:" headers as specified by CURLOPT_MAXREDIRS
CURLOPT_FOLLOWLOCATION => 1,
// include the response header(s) as a property of the object given as argument to the callback
CURLOPT_HEADER => 1,
// the maximum amount of HTTP redirections to follow; used together with CURLOPT_FOLLOWLOCATION
CURLOPT_MAXREDIRS => 50,
// the maximum number of seconds to allow cURL functions to execute before timing out
CURLOPT_TIMEOUT => 30,
// most services/websites will block requests with no/invalid user agents
// note that the user agent string is random and will change whenever the library is instantiated!
CURLOPT_USERAGENT => $this->_user_agent(),
// return the transfer as a string of instead of outputting it to the screen
CURLOPT_RETURNTRANSFER => 1,
));
// set defaults for accessing HTTPS servers
$this->ssl();
// caching is disabled by default
$this->cache(false);
}
/**
* Use this method to enable caching of requests.
*
* <i>Note that only the actual request is cached and not associated downloads, if any!</i>
*
* <i>Caching is disabled by default!</i>
*
* <code>
* // the callback function to be executed for each and every
* // request, as soon as a request finishes
* // the callback function receives as argument an object with 4 properties
* // (info, header, body and response)
* function mycallback($result) {
*
* // everything went well at cURL level
* if ($result->response[1] == CURLE_OK) {
*
* // if server responded with code 200 (meaning that everything went well)
* // see http://httpstatus.es/ for a list of possible response codes
* if ($result->info['http_code'] == 200) {
*
* // see all the returned data
* print_r('<pre>');
* print_r($result);
*
* // show the server's response code
* } else die('Server responded with code ' . $result->info['http_code']);
*
* // something went wrong
* // ($result still contains all data that could be gathered)
* } else die('cURL responded with: ' . $result->response[0]);
*
* }
*
* // include the Zebra_cURL library
* require 'path/to/Zebra_cURL';
*
* // instantiate the Zebra_cURL object
* $curl = new Zebra_cURL();
*
* // cache results in the "cache" folder and for 86400 seconds (24 hours)
* $curl->cache('cache', 86400);
*
* // let's fetch the RSS feeds of some popular tech-related websites
* // execute the "mycallback" function for each request, as soon as it finishes
* $curl->get(array(
* 'http://feeds.feedburner.com/alistapart/main',
* 'http://feeds.feedburner.com/TechCrunch',
* 'http://feeds.mashable.com/mashable',
* ), 'mycallback')
* </code>
*
* @param string $path Path where cache files to be stored.
*
* Setting this to FALSE will disable caching.
*
* <i>Unless set to FALSE, this must point to a writable directory or an error will
* be triggered!</i>
*
* @param integer $lifetime (Optional) The number of seconds after which cache will be considered expired.
*
* Default is 3600 (one hour).
*
* @param boolean $compress (Optional) If set to TRUE, cache files will be
* {@link http://php.net/manual/ro/function.gzcompress.php gzcompress}-ed so that
* they occupy less disk space.
*
* Default is TRUE.
*
* @param octal $chmod (Optional) The file system permissions to be set for newly created cache files.
*
* I suggest using the value "0755" (without the quotes) but, if you know what you
* are doing, here is how you can calculate the permission levels:
*
* - 400 Owner Read
* - 200 Owner Write
* - 100 Owner Execute
* - 40 Group Read
* - 20 Group Write
* - 10 Group Execute
* - 4 Global Read
* - 2 Global Write
* - 1 Global Execute
*
* Default is "0755" (without the quotes).
*
* @return null
*/
public function cache($path, $lifetime = 3600, $compress = true, $chmod = 0755)
{
// if caching is not explicitly disabled
if ($path != false)
// save cache-related properties
$this->cache = array(
'path' => $path,
'lifetime' => $lifetime,
'chmod' => $chmod,
'compress' => $compress,
);
// if caching is explicitly disabled, set this property to FALSE
else $this->cache = false;
}
/**
* Sets the path and name of the file to save to / retrieve cookies from. All cookie data will be stored in this
* file on a per-domain basis. Important when cookies need to stored/restored to maintain status/session of requests
* made to the same domains.
*
* This method will automatically set the <b>CURLOPT_COOKIEJAR</b> and <b>CURLOPT_COOKIEFILE</b> options.
*
* @param string $path The path to a file to save to / retrieve cookies from.
*
* If file does not exist the library will attempt to create it, and if it is unable to
* create it will trigger an error.
*
* @param boolean $keep (Optional) By default, the file to save to / retrieve cookies from is deleted when
* script execution finishes. If you want the file to be preserved, set this argument to
* TRUE.
*
* Default is FALSE.
*
* @return null
*/
public function cookies($path, $keep = false)
{
// file does not exist
if (!is_file($path)) {
// attempt to create it
if (!($handle = fopen($path, 'a')))
// if file could not be created, trigger an error
trigger_error('File "' . $path . '" for storing cookies could not be found nor could it automatically be created! Make sure either that the path to the file points to a writable directory, or create the file yourself and make it writable', E_USER_ERROR);
// if file could be create, release handle
fclose($handle);
}
// set these options
$this->option(array(
CURLOPT_COOKIEJAR => $path,
CURLOPT_COOKIEFILE => $path,
));
}
/**
* Downloads one or more files from one or more URLs specified by the <i>$urls</i> argument, saves the downloaded
* files (with their original name) to the path specified by the <i>$path</i> argument, and executes the callback
* function specified by the <i>$callback</i> argument for each and every request, as soon as a request finishes.
*
* Downloads are streamed (bytes downloaded are directly written to disk) removing the unnecessary strain from your
* server of reading files into memory first, and then writing them to disk.
*
* This method will automatically set the following options:
*
* - <b>CURLINFO_HEADER_OUT</b> - TRUE
* - <b>CURLOPT_BINARYTRANSFER</b> - TRUE
* - <b>CURLOPT_HEADER</b> - TRUE
* - <b>CURLOPT_FILE</b>
*
* ...and will unset the following options:
*
* - <b>CURLOPT_HTTPGET</b>
* - <b>CURLOPT_NOBODY</b>
* - <b>CURLOPT_POST</b>
* - <b>CURLOPT_POSTFIELDS</b>
* - <b>CURLOPT_USERPWD</b>
*
* Files are downloaded preserving their original names, so you may want to check that if you are downloading more
* files having the same name!
*
* Multiple requests are processed asynchronously, in parallel, and the callback function is called for each and every
* request, as soon as a request finishes. The number of parallel requests to be constantly processed, at all times,
* can be set through the {@link threads} property. See also the {@link $pause_interval pause_interval} property.
*
* <i>Note that requests may not finish in the same order as initiated!</i>
*
* <code>
* // the callback function to be executed for each and every
* // request, as soon as a request finishes
* // the callback function receives as argument an object with 4 properties
* // (info, header, body and response)
* function mycallback($result) {
*
* // everything went well at cURL level
* if ($result->response[1] == CURLE_OK) {
*
* // if server responded with code 200 (meaning that everything went well)
* // see http://httpstatus.es/ for a list of possible response codes
* if ($result->info['http_code'] == 200) {
*
* // see all the returned data
* print_r('<pre>');
* print_r($result);
*
* // show the server's response code
* } else die('Server responded with code ' . $result->info['http_code']);
*
* // something went wrong
* // ($result still contains all data that could be gathered)
* } else die('cURL responded with: ' . $result->response[0]);
*
* }
*
* // include the Zebra_cURL library
* require 'path/to/Zebra_cURL';
*
* // instantiate the Zebra_cURL object
* $curl = new Zebra_cURL();
*
* // download 2 images from 2 different websites, and
* // execute the "mycallback" function for each request, as soon as it finishes
* $curl->download(array(
* 'http://www.somewebsite.com/images/alpha.jpg',
* 'http://www.otherwebsite.com/images/omega.jpg',
* ), 'destination/path/', 'mycallback');
* </code>
*
* @param mixed $urls A single URL or an array of URLs to process.
*
* @param string $path The path to where to save the file(s) to.
*
* If path is not pointing to a directory or is not writable, the library will
* trigger an error.
*
* @param mixed $callback (Optional) Callback function to be called as soon as a request finishes.
*
* May be given as a string representing a name of an existing function, as an
* anonymous function created on the fly via {@link http://www.php.net/manual/ro/function.create-function.php
* create_function} or, as of PHP 5.3.0, via a {@link http://www.php.net/manual/ro/function.create-function.php
* closure}.
*
* The callback function receives as first argument <b>an object</b> with <b>4
* properties</b> as described below, while any further arguments passed to the
* {@link download} method will be passed as extra arguments to the callback function:
*
* - <b>info</b> - an associative array containing information about the
* request that just finished, as returned by PHP's
* {@link http://php.net/manual/en/function.curl-getinfo.php curl_getinfo()}
* function; there's also an extra entry called <i>original_url</i>
* because, as curl_getinfo() only returns information
* about the <b>last</b> request, the original URL may
* be lost otherwise.
*
* - <b>headers</b> - an associative array with 2 items:
*
* <b>- last_request</b> an array with a single entry
* containing the request headers generated by <i>the
* last request</i>; so, remember, if there are redirects
* involved, there will be more requests made, but only
* information from the last one will be available; if
* explicitly disabled via the {@link option()} method
* by setting <b>CURLINFO_HEADER_OUT</b> to 0 or FALSE,
* this will be an empty string;
*
* <b>- responses</b> an empty string as it is not
* available for this method;
*
* <i>Unless disabled, each entry in the headers' array
* is an associative array in the form of property =>
* value</i>
*
* - <b>body</b> - an empty string as it is not available for this method;
*
* - <b>response</b> - the response given by the cURL library as an array with
* 2 entries: the first entry is the textual representation
* of the result's code, while second is the result's code
* itself; if the request was successful, these values will
* be <i>array(CURLE_OK, 0);</i> consult
* {@link http://www.php.net/manual/en/function.curl-errno.php#103128 this list}
* to see the possible values of this property;
*
* @return null
*/
public function download($urls, $path, $callback = '')
{
// if destination path is not a directory or is not writable, trigger an error message
if (!is_dir($path) || !is_writable($path)) trigger_error('"' . $path . '" is not a valid path or is not writable', E_USER_ERROR);
// prior to PHP 5.3, func_get_args() cannot be used as a function parameter, so we need this intermediary step
$arguments = func_get_args();
// iterate through the list of URLs to process
foreach ((array)$urls as $url)
// add each URL and associated properties to the "_requests" property
$this->_requests[] = array(
'type' => 'download',
'url' => $url,
'path' => rtrim($path, '/\\') . '/',
'options' => array(
CURLINFO_HEADER_OUT => 1,
CURLOPT_BINARYTRANSFER => 1,
CURLOPT_HEADER => 0,
CURLOPT_HTTPGET => null,
CURLOPT_NOBODY => null,
CURLOPT_POST => null,
CURLOPT_POSTFIELDS => null,
CURLOPT_USERPWD => null,
),
'callback' => $callback,
// additional arguments to pass to the callback function, if any
'arguments' => array_slice($arguments, 3),
);
// if we're just queuing requests for now, do not execute the next lines
if ($this->_queue) return;
// if we have to pause between batches of requests, process them sequentially, in batches
if ($this->pause_interval > 0) $this->_process_paused();
// if we don't have to pause between batches of requests, process them all at once
else $this->_process();
}
/**
* Works exactly like the {@link download()} method only that downloads are made from an FTP server.
*
* Downloads from an FTP server to which the connection is made using the given <i>$username</i> and <i>$password</i>
* arguments, one or more files specified by the <i>$urls</i> argument, saves the downloaded files (with their original
* name) to the path specified by the <i>$path</i> argument, and executes the callback function specified by the
* <i>$callback</i> argument for each and every request, as soon as a request finishes.
*
* Downloads are streamed (bytes downloaded are directly written to disk) removing the unnecessary strain from your
* server of reading files into memory first, and then writing them to disk.
*
* This method will automatically set the following options:
*
* - <b>CURLINFO_HEADER_OUT</b> - TRUE
* - <b>CURLOPT_BINARYTRANSFER</b> - TRUE
* - <b>CURLOPT_HEADER</b> - TRUE
* - <b>CURLOPT_FILE</b>
* - <b>CURLOPT_USERPWD</b>
*
* ...and will unset the following options:
*
* - <b>CURLOPT_HTTPGET</b>
* - <b>CURLOPT_NOBODY</b>
* - <b>CURLOPT_POST</b>
* - <b>CURLOPT_POSTFIELDS</b>
* - <b>CURLOPT_USERPWD</b>
*
* Files are downloaded preserving their name so you may want to check that, if you are downloading more images
* having the same name (either from the same, or from different servers)!
*
* Multiple requests are processed asynchronously, in parallel, and the callback function is called for each and every
* request, as soon as a request finishes. The number of parallel requests to be constantly processed, at all times,
* can be set through the {@link threads} property. See also the {@link $pause_interval pause_interval} property.
*
* <i>Note that requests may not finish in the same order as initiated!</i>
*
* <code>
* // the callback function to be executed for each and every
* // request, as soon as a request finishes
* // the callback function receives as argument an object with 4 properties
* // (info, header, body and response)
* function mycallback($result) {
*
* // everything went well at cURL level
* if ($result->response[1] == CURLE_OK) {
*
* // if server responded with code 200 (meaning that everything went well)
* // see http://httpstatus.es/ for a list of possible response codes
* if ($result->info['http_code'] == 200) {
*
* // see all the returned data
* print_r('<pre>');
* print_r($result);
*
* // show the server's response code
* } else die('Server responded with code ' . $result->info['http_code']);
*
* // something went wrong
* // ($result still contains all data that could be gathered)
* } else die('cURL responded with: ' . $result->response[0]);
*
* }
*
* // include the Zebra_cURL library
* require 'path/to/Zebra_cURL';
*
* // instantiate the Zebra_cURL object
* $curl = new Zebra_cURL();
*
* // connect to the FTP server using the given credential, download a file to a given location and
* // execute the "mycallback" function for each request, as soon as it finishes
* $curl->ftp_download('ftp://somefile.ext', 'destination/path', 'username', 'password', 'mycallback');
* </code>
*
* @param mixed $urls A single URL or an array of URLs to process.
*
* @param string $path The path to where to save the file(s) to.
*
* If path is not pointing to a directory or is not writable, the library will
* trigger an error.
*
* @param string $username (Optional) The username to be used to connect to the FTP server (if required).
*
* @param string $password (Optional) The password to be used to connect to the FTP server (if required).
*
* @param mixed $callback (Optional) Callback function to be called as soon as a request finishes.
*
* May be given as a string representing a name of an existing function, as an
* anonymous function created on the fly via {@link http://www.php.net/manual/ro/function.create-function.php
* create_function} or, as of PHP 5.3.0, via a {@link http://www.php.net/manual/ro/function.create-function.php
* closure}.
*
* The callback function receives as first argument <b>an object</b> with <b>4
* properties</b> as described below, while any further arguments passed to the
* {@link ftp_download} method will be passed as extra arguments to the callback function:
*
* - <b>info</b> - an associative array containing information about the
* request that just finished, as returned by PHP's
* {@link http://php.net/manual/en/function.curl-getinfo.php curl_getinfo()}
* function;
*
* - <b>headers</b> - an associative array with 2 items:
*
* <b>- last_request</b> an array with a single entry
* containing the request headers generated by <i>the
* last request</i>; so, remember, if there are redirects
* involved, there will be more requests made, but only
* information from the last one will be available; if
* explicitly disabled via the {@link option()} method
* by setting <b>CURLINFO_HEADER_OUT</b> to 0 or FALSE,
* this will be an empty string;
*
* <b>- responses</b> an empty string as it is not
* available for this method;
*
* <i>Unless disabled, each entry in the headers' array
* is an associative array in the form of property =>
* value</i>
*
* - <b>body</b> - an empty string as it is not available for this method;
*
* - <b>response</b> - the response given by the cURL library as an array with
* 2 entries: the first entry is the textual representation
* of the result's code, while second is the result's code
* itself; if the request was successful, these values will
* be <i>array(CURLE_OK, 0);</i> consult
* {@link http://www.php.net/manual/en/function.curl-errno.php#103128 this list}
* to see the possible values of this property;
*
* @return null
*/
public function ftp_download($urls, $path, $username = '', $password = '', $callback = '')
{
// if destination path is not a directory or is not writable, trigger an error message
if (!is_dir($path) || !is_writable($path)) trigger_error('"' . $path . '" is not a valid path or is not writable', E_USER_ERROR);
// iterate through the list of URLs to process
foreach ((array)$urls as $url)
// add each URL and associated properties to the "_requests" property
$this->_requests[] = array(
'type' => 'download',
'url' => $url,
'path' => rtrim($path, '/\\') . '/',
'options' => array(
CURLINFO_HEADER_OUT => 1,
CURLOPT_BINARYTRANSFER => 1,
CURLOPT_HEADER => 0,
CURLOPT_USERPWD => $username != '' ? $username . ':' . $password : null,
CURLOPT_HTTPGET => null,
CURLOPT_NOBODY => null,
CURLOPT_POST => null,
CURLOPT_POSTFIELDS => null,
),
'callback' => $callback,
// additional arguments to pass to the callback function, if any
'arguments' => array_slice($arguments, 5),
);
// if we're just queuing requests for now, do not execute the next lines
if ($this->_queue) return;
// if we have to pause between batches of requests, process them sequentially, in batches
if ($this->pause_interval > 0) $this->_process_paused();
// if we don't have to pause between batches of requests, process them all at once
else $this->_process();
}
/**
* Performs an HTTP <b>GET</b> request to one or more URLs specified by the <i>$urls</i> argument and executes the
* callback function specified by the <i>$callback</i> argument for each and every request, as soon as a request
* finishes.
*
* This method will automatically set the following options:
*
* - <b>CURLINFO_HEADER_OUT</b> - TRUE
* - <b>CURLOPT_HEADER</b> - TRUE
* - <b>CURLOPT_HTTPGET</b> - TRUE
* - <b>CURLOPT_NOBODY</b> - FALSE
*
* ...and will unset the following options:
*
* - <b>CURLOPT_BINARYTRANSFER</b>
* - <b>CURLOPT_FILE</b>
* - <b>CURLOPT_POST</b>
* - <b>CURLOPT_POSTFIELDS</b>
* - <b>CURLOPT_USERPWD</b>
*
* Multiple requests are processed asynchronously, in parallel, and the callback function is called for each and every
* request, as soon as a request finishes. The number of parallel requests to be constantly processed, at all times,
* can be set through the {@link threads} property. See also the {@link $pause_interval pause_interval} property.
*
* <i>Note that requests may not finish in the same order as initiated!</i>
*
* <code>
* // the callback function to be executed for each and every
* // request, as soon as a request finishes
* // the callback function receives as argument an object with 4 properties
* // (info, header, body and response)
* function mycallback($result) {
*
* // everything went well at cURL level
* if ($result->response[1] == CURLE_OK) {
*
* // if server responded with code 200 (meaning that everything went well)
* // see http://httpstatus.es/ for a list of possible response codes
* if ($result->info['http_code'] == 200) {
*
* // see all the returned data
* print_r('<pre>');
* print_r($result);
*
* // show the server's response code
* } else die('Server responded with code ' . $result->info['http_code']);
*
* // something went wrong
* // ($result still contains all data that could be gathered)
* } else die('cURL responded with: ' . $result->response[0]);
*
* }
*
* // include the Zebra_cURL library
* require 'path/to/Zebra_cURL';
*
* // instantiate the Zebra_cURL object
* $curl = new Zebra_cURL();
*
* // cache results in the "cache" folder and for 3600 seconds (one hour)
* $curl->cache('cache', 3600);
*
* // let's fetch the RSS feeds of some popular websites
* // execute the "mycallback" function for each request, as soon as it finishes
* $curl->get(array(
* 'http://feeds.feedburner.com/alistapart/main',
* 'http://feeds.feedburner.com/TechCrunch',
* 'http://feeds.mashable.com/mashable',
* ), 'mycallback')
* </code>
*
* @param mixed $urls A single URL or an array of URLs to process.
*
* @param mixed $callback (Optional) Callback function to be called as soon as a request finishes.
*
* May be given as a string representing a name of an existing function, as an anonymous
* function created on the fly via {@link http://www.php.net/manual/ro/function.create-function.php
* create_function} or, as of PHP 5.3.0, via a {@link http://www.php.net/manual/ro/function.create-function.php
* closure}.
*
* The callback function receives as first argument <b>an object</b> with <b>4 properties</b>
* as described below, while any further arguments passed to the {@link get} method will
* be passed as extra arguments to the callback function:
*
* - <b>info</b> - an associative array containing information about the request
* that just finished, as returned by PHP's
* {@link http://php.net/manual/en/function.curl-getinfo.php curl_getinfo()}
* function;
*
* - <b>headers</b> - an associative array with 2 items:
*
* <b>- last_request</b> an array with a single entry containing
* the request headers generated by <i>the last request</i>; so,
* remember, if there are redirects involved, there will be more
* requests made, but only information from the last one will be
* available;
*
* <b>- responses</b> an array with one or more entries (if there
* are redirects involved) with the response headers of all the
* requests made;
*
* <i>Each entry in the headers' array is an associative array
* in the form of property => value</i>
*
* - <b>body</b> - the response of the request (the content of the page at the
* URL).
*
* Unless disabled via the {@link __construct() constructor}, all
* applicable characters will be converted to HTML entities via
* PHP's {@link http://php.net/manual/en/function.htmlentities.php htmlentities()}
* function, so remember to use PHP's {@link http://www.php.net/manual/en/function.html-entity-decode.php html_entity_decode()}
* function to do reverse this, if it's the case;
*
* - <b>response</b> - the response given by the cURL library as an array with 2
* entries: the first entry is the textual representation of the
* result's code, while second is the result's code itself; if
* the request was successful, these values will be
* <i>array(CURLE_OK, 0);</i> consult
* {@link http://www.php.net/manual/en/function.curl-errno.php#103128 this list}
* to see the possible values of this property;
*
* <samp>If the callback function returns FALSE while {@link cache} is enabled, the library will not cache the
* respective request, making it easy to retry failed requests without having to clear all cache.</samp>
*
* @return null
*/
public function get($urls, $callback = '')
{
// prior to PHP 5.3, func_get_args() cannot be used as a function parameter, so we need this intermediary step
$arguments = func_get_args();
// iterate through the list of URLs to process
foreach ((array)$urls as $url)
// add each URL and associated properties to the "_requests" property
$this->_requests[] = array(
'type' => 'get',
'url' => $url,
'options' => array(
CURLINFO_HEADER_OUT => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPGET => 1,
CURLOPT_NOBODY => 0,
CURLOPT_BINARYTRANSFER => null,
CURLOPT_FILE => null,
CURLOPT_POST => null,
CURLOPT_POSTFIELDS => null,
CURLOPT_USERPWD => null,
),
'callback' => $callback,
// additional arguments to pass to the callback function, if any
'arguments' => array_slice($arguments, 3),
);
// if we're just queuing requests for now, do not execute the next lines
if ($this->_queue) return;
// if we have to pause between batches of requests, process them sequentially, in batches
if ($this->pause_interval > 0) $this->_process_paused();