-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathZebra_cURL.php
3089 lines (2676 loc) · 137 KB
/
Zebra_cURL.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
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
/**
* A high-performance solution for making HTTP requests from your PHP projects.
*
* Zebra cURL allows you to run multiple requests concurrently, asynchronously, and supports a wide range of HTTP methods,
* including GET, POST, HEADER, PUT, PATCH, and DELETE. In addition to basic requests, this library also offers support
* for caching, FTP downloads, HTTP authentication, and proxy requests. This makes it a versatile tool for a wide range
* of applications and environments. Whether you're working on a simple script or a complex system, Zebra cURL can help
* you streamline your workflow and improve your application's performance.
*
* Read more {@link https://github.com/stefangabos/Zebra_cURL/ here}.
*
* @author Stefan Gabos <[email protected]>
* @version 1.6.4 (last revision: December 13, 2024)
* @copyright © 2013 - 2024 Stefan Gabos
* @license https://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} property and then wait for {@link 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} running at all times
* 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 once.
*
* <code>
* // process 30 simultaneous requests at once
* $curl->threads = 30;
* </code>
*
* Note that unless {@link pause_interval} is set to a value greater than `0`, the library will process a constant
* number of requests, at all times; it is doing this by starting a new request as soon as another one finishes.
*
* If {@link pause_interval} is set to a value greater than `0`, the library will process as many requests as set
* by the {@link threads} property and then wait for {@link pause_interval} seconds before processing the next
* batch of requests.
*
* Default is `10`
*
* @var integer
*/
public $threads;
/**
* Used by the {@cache} method to cache request details
*
* @var array<mixed>|boolean
* @access private
*/
private $cache;
/**
* Used by the {@link option} method to store the cURL options.
*
* @var array<int>
* @access private
*/
private $options;
/**
* Used by the {@link _process} method to determine whether to run processed requests' bodies through PHP's
* {@link https://php.net/manual/en/function.htmlentities.php htmlentities} function.
*
* Default is TRUE. Can be changed by instantiating the library with the FALSE argument.
*
* @var boolean
* @access private
*/
private $_htmlentities;
/**
* Used to tell the library whether to queue requests or to process them right away
*
* @var boolean
* @access private
*/
private $_queue;
/**
* The cURL multi handle
*
* @var resource|boolean
* @access private
*/
private $_multi_handle;
/**
* Used to keep track of all the requests that need to be processed.
*
* @var array<mixed>
* @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<mixed>
* @access private
*/
private $_running;
/**
* As of PHP 8 we use an extra map as a helper.
*
* @var array<string>
* @access private
*/
private $_running_map;
/**
* Possible values of the "result" attribute in the object passed to the callback function.
* List is kept up to date with the {@link https://github.com/curl/curl/blob/master/include/curl/curl.h source code of curl}
*
* @var array<string>
* @access private
*/
private $_response_messages = array(
0 => 'CURLE_OK',
1 => 'CURLE_UNSUPPORTED_PROTOCOL',
2 => 'CURLE_FAILED_INIT',
3 => 'CURLE_URL_MALFORMAT',
4 => 'CURLE_NOT_BUILT_IN',
5 => 'CURLE_COULDNT_RESOLVE_PROXY',
6 => 'CURLE_COULDNT_RESOLVE_HOST',
7 => 'CURLE_COULDNT_CONNECT',
8 => 'CURLE_WEIRD_SERVER_REPLY',
9 => 'CURLE_REMOTE_ACCESS_DENIED',
10 => 'CURLE_FTP_ACCEPT_FAILED',
11 => 'CURLE_FTP_WEIRD_PASS_REPLY',
12 => 'CURLE_FTP_ACCEPT_TIMEOUT',
13 => 'CURLE_FTP_WEIRD_PASV_REPLY',
14 => 'CURLE_FTP_WEIRD_227_FORMAT',
15 => 'CURLE_FTP_CANT_GET_HOST',
16 => 'CURLE_HTTP2',
17 => 'CURLE_FTP_COULDNT_SET_TYPE',
18 => 'CURLE_PARTIAL_FILE',
19 => 'CURLE_FTP_COULDNT_RETR_FILE',
20 => 'CURLE_OBSOLETE20', // NOT USED
21 => 'CURLE_QUOTE_ERROR',
22 => 'CURLE_HTTP_RETURNED_ERROR',
23 => 'CURLE_WRITE_ERROR',
24 => 'CURLE_OBSOLETE24', // NOT USED
25 => 'CURLE_UPLOAD_FAILED',
26 => 'CURLE_READ_ERROR',
27 => 'CURLE_OUT_OF_MEMORY',
28 => 'CURLE_OPERATION_TIMEDOUT',
29 => 'CURLE_OBSOLETE29', // NOT USED
30 => 'CURLE_FTP_PORT_FAILED',
31 => 'CURLE_FTP_COULDNT_USE_REST',
32 => 'CURLE_OBSOLETE32', // NOT USED
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',
40 => 'CURLE_OBSOLETE40', // NOT USED
41 => 'CURLE_FUNCTION_NOT_FOUND', // NOT USED since with 7.53.0
42 => 'CURLE_ABORTED_BY_CALLBACK',
43 => 'CURLE_BAD_FUNCTION_ARGUMENT',
44 => 'CURLE_OBSOLETE44', // NOT USED
45 => 'CURLE_INTERFACE_FAILED',
46 => 'CURLE_OBSOLETE46', // NOT USED
47 => 'CURLE_TOO_MANY_REDIRECTS',
48 => 'CURLE_UNKNOWN_OPTION',
49 => 'CURLE_SETOPT_OPTION_SYNTAX',
50 => 'CURLE_OBSOLETE50', // NOT USED
51 => 'CURLE_OBSOLETE51', // NOT USED
52 => 'CURLE_GOT_NOTHING',
53 => 'CURLE_SSL_ENGINE_NOTFOUND',
54 => 'CURLE_SSL_ENGINE_SETFAILED',
55 => 'CURLE_SEND_ERROR',
56 => 'CURLE_RECV_ERROR',
57 => 'CURLE_OBSOLETE57', // NOT USED
58 => 'CURLE_SSL_CERTPROBLEM',
59 => 'CURLE_SSL_CIPHER',
60 => 'CURLE_PEER_FAILED_VERIFICATION',
61 => 'CURLE_BAD_CONTENT_ENCODING',
62 => 'CURLE_OBSOLETE62', // NOT USED since 7.82.0
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_OBSOLETE75', // NOT USED since 7.82.0
76 => 'CURLE_OBSOLETE76', // NOT USED since 7.82.0
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',
89 => 'CURLE_NO_CONNECTION_AVAILABLE',
90 => 'CURLE_SSL_PINNEDPUBKEYNOTMATCH',
91 => 'CURLE_SSL_INVALIDCERTSTATUS',
92 => 'CURLE_HTTP2_STREAM',
93 => 'CURLE_RECURSIVE_API_CALL',
94 => 'CURLE_AUTH_ERROR',
95 => 'CURLE_HTTP3',
96 => 'CURLE_QUIC_CONNECT_ERROR',
97 => 'CURLE_PROXY',
98 => 'CURLE_SSL_CLIENTCERT',
99 => 'CURLE_UNRECOVERABLE_POLL',
100 => 'CURLE_TOO_LARGE',
101 => 'CURLE_ECH_REQUIRED',
);
/**
* Stores the result of a call to the {@link scrape} method
*
* @var mixed
*
* @access private
*/
private $_scrape_result;
/**
* Constructor of the class.
*
* Below is the list of default options set by the library when instantiated. Various methods of the library may
* overwrite some of these options when called (see {@link delete}, {@link download}, {@link ftp_download}, {@link get},
* {@link header}, {@link post}, {@link put}). The value of any of these options may also be changed with the
* {@link option} method. For a full list of available options and their description, consult the
* {@link https://www.php.net/manual/en/function.curl-setopt.php PHP documentation}.
*
* - `CURLINFO_HEADER_OUT` - the last request string sent<br>
* default: `TRUE`
*
* - `CURLOPT_AUTOREFERER` - TRUE to automatically set the *"Referer:"* field in requests where it follows
* a *"Location:"* redirect<br>
* default: `TRUE`
*
*
* - `CURLOPT_COOKIEFILE` - the name of the file containing the cookie data. the cookie file can be in
* Netscape format, or just plain HTTP-style headers dumped into a file. if the
* name is an empty string, no cookies are loaded, but cookie handling is still
* enabled<br>
* default: `an empty string`
*
* - `CURLOPT_CONNECTTIMEOUT` - the number of seconds to wait while trying to connect<br>
* default: `10` (use `0` to wait indefinitely)
*
* - `CURLOPT_ENCODING` - the contents of the "Accept-Encoding: " header. this enables decoding of the
* response. supported encodings are *identity*, *deflate*, and *gzip*. if an
* empty string is set, a header containing all supported encoding types is sent<br>
* default: `gzip,deflate`
*
* - `CURLOPT_FOLLOWLOCATION` - TRUE to follow any *"Location:"* header that the server sends as part of the
* HTTP header (note this is recursive, PHP will follow as many *"Location:"*
* headers that it is sent, unless `CURLOPT_MAXREDIRS` is set - see below)<br>
* default: `TRUE`
*
* - `CURLOPT_HEADER` - TRUE to include the header in the output<br>
* default: `TRUE`
*
* - `CURLOPT_MAXREDIRS` - the maximum amount of HTTP redirections to follow. use this option alongside
* `CURLOPT_FOLLOWLOCATION` - see above<br>
* default: `50`
*
* - `CURLOPT_RETURNTRANSFER` - TRUE to return the transfer's body as a string instead of outputting it
* directly<br>
* default: `TRUE`
*
* - `CURLOPT_SSL_VERIFYHOST` - 1 to check the existence of a common name in the SSL peer certificate. 2 to
* check the existence of a common name and also verify that it matches the
* hostname provided. 0 to not check the names<br>
* see the {@link ssl} method for more info<br>
* default: `TRUE`
*
* - `CURLOPT_SSL_VERIFYPEER` - FALSE to stop cURL from verifying the peer's certificate<br>
* see the {@link ssl} method for more info<br>
* default: `TRUE`
*
* - `CURLOPT_TIMEOUT` - the maximum number of seconds to allow cURL functions to execute<br>
* default: `10`
*
* - `CURLOPT_USERAGENT` - 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 (Optional) Instructs the script whether the response body returned by the
* {@link get} and {@link post} methods should be run through PHP's
* {@link https://php.net/manual/en/function.htmlentities.php htmlentities}
* function.
*
* Default is `TRUE`
*
* @return void
*/
public 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->_running_map = $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 redirects 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,
));
// if PHP version is at least 5.5
if (version_compare(PHP_VERSION, '5.5') >= 0)
// disable usage of @ in POST arguments
// see https://wiki.php.net/rfc/curl-file-upload
$this->option(CURLOPT_SAFE_UPLOAD, true);
// set defaults for accessing HTTPS servers
$this->ssl();
// caching is disabled by default
$this->cache(false);
}
/**
* Enables caching of request results.
*
* > Note that in case of downloads, only the actual request is cached and not the associated downloads
*
* <code>
* // instantiate the class
* $curl = new Zebra_cURL();
*
* // if making requests over HTTPS we need to load a CA bundle
* // so we don't get CURLE_SSL_CACERT response from cURL
* // you can get this bundle from https://curl.se/docs/caextract.html
* $curl->ssl(true, 2, 'path/to/cacert.pem');
*
* // cache results in the "cache" folder and for 86400 seconds (24 hours)
* $curl->cache('cache', 86400);
*
* // fetch the RSS feeds of some popular tech-related websites
* // and execute a callback function for each request, as soon as it finishes
* $curl->get(array(
*
* 'https://alistapart.com/main/feed/',
* 'https://www.smashingmagazine.com/feed/',
* 'https://code.tutsplus.com/posts.atom',
*
* // the callback function receives as argument an object with 4 properties
* // (info, header, body and response)
* ), function($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 https://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 trigger_error('Server responded with code ' . $result->info['http_code'], E_USER_ERROR);
*
* // something went wrong
* // ($result still contains all data that could be gathered)
* } else trigger_error('cURL responded with: ' . $result->response[0], E_USER_ERROR);
*
* });
* </code>
*
* @param mixed $path Path where cache files to be stored.
*
* Setting this to `FALSE` will disable caching.
*
* *If set to a non-existing path, the library will try to create the folder
* and will trigger an error if, for whatever reasons, it is unable to do so. If the
* folder can be created, its permissions will be set to the value of the $chmod
* argument.*
*
* @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 https://php.net/manual/en/function.gzcompress.php gzcompress}-ed so that
* they occupy less disk space.
*
* Default is `TRUE`.
*
* @param integer $chmod (Optional) The file system permissions to be set for newly created cache files.
*
* I suggest using the value `0755` 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`.
*
* @return void
*/
public function cache($path, $lifetime = 3600, $compress = true, $chmod = 0755) {
// if caching is not explicitly disabled
if ($path !== false) {
// if path doesn't exist, attempt to create it
if (!is_dir($path)) @mkdir($path, $chmod, true);
// 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 cookie 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 `CURLOPT_COOKIEJAR` and `CURLOPT_COOKIEFILE` options.
*
* @param string $path The path to a file to save cookies to / retrieve cookies from.
*
* *If file does not exist the library will attempt to create it and, if it is unable to
* do so, it will trigger an error.*
*
* @return void
*/
public function cookies($path) {
// 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, // for writing
CURLOPT_COOKIEFILE => $path, // for reading
));
}
/**
* Performs an HTTP `DELETE` request to one or more URLs with optional POST data, and executes the callback
* function specified by the *$callback* argument for each and every request, as soon as the request finishes.
*
* This method will automatically set the following options:
*
* - `CURLINFO_HEADER_OUT` = `TRUE`
* - `CURLOPT_CUSTOMREQUEST` = `DELETE`
* - `CURLOPT_HEADER` = `TRUE`
* - `CURLOPT_NOBODY` = `FALSE`
* - `CURLOPT_POST` = `FALSE`
* - `CURLOPT_POSTFIELDS` = the POST data
*
* ...and will unset the following options:
*
* - `CURLOPT_BINARYTRANSFER`
* - `CURLOPT_HTTPGET`
* - `CURLOPT_FILE`
*
* Multiple requests are processed asynchronously, in parallel, and the callback function is called for each and every
* request as soon as the request finishes. The number of parallel requests to be constantly processed, at all times,
* is set through the {@link threads} property. See also {@link pause_interval}.
*
* > Because requests are done asynchronously, when initiating multiple requests at once, these may not finish in
* the order in which they were initiated!
*
* <code>
* // instantiate the class
* $curl = new Zebra_cURL();
*
* // if making requests over HTTPS we need to load a CA bundle
* // so we don't get CURLE_SSL_CACERT response from cURL
* // you can get this bundle from https://curl.se/docs/caextract.html
* $curl->ssl(true, 2, 'path/to/cacert.pem');
*
* // do a DELETE request
* // and execute a callback function for each request, as soon as it finishes
* $curl->delete(array(
*
* 'https://www.somewebsite.com' => array(
* 'data_1' => 'value 1',
* 'data_2' => 'value 2',
* ),
*
* // the callback function receives as argument an object with 4 properties
* // (info, header, body and response)
* ), function($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 https://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 trigger_error('Server responded with code ' . $result->info['http_code'], E_USER_ERROR);
*
* // something went wrong
* // ($result still contains all data that could be gathered)
* } else trigger_error('cURL responded with: ' . $result->response[0], E_USER_ERROR);
*
* });
* </code>
*
* @param mixed $urls URL(s) to send the request(s) to.
*
* Read full description of the argument at the {@link post} method.
*
* @param mixed $callback (Optional) Callback function to be called as soon as the request finishes.
*
* Read full description of the argument at the {@link get} method.
*
* @since 1.3.3
*
* @return void
*/
public function delete($urls, $callback = '') {
// normalize URLs
// (transforms every allowed combination to the same type of array)
$urls = $this->_prepare_urls($urls);
// iterate through the list of URLs to process
foreach ($urls as $values)
// add each URL and associated properties to the "_requests" property
$this->_requests[] = array(
'url' => $values['url'],
// merge any custom options with the default ones
'options' =>
(isset($values['options']) ? $values['options'] : array()) +
array(
CURLINFO_HEADER_OUT => 1,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_HEADER => 1,
CURLOPT_NOBODY => 0,
CURLOPT_POST => 0,
CURLOPT_POSTFIELDS => isset($values['data']) ? $values['data'] : '',
CURLOPT_BINARYTRANSFER => null,
CURLOPT_HTTPGET => null,
CURLOPT_FILE => null,
),
'callback' => $callback,
// additional arguments to pass to the callback function, if any
'arguments' => array_slice(func_get_args(), 2, null, true),
);
// 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();
}
/**
* Downloads one or more files from one or more URLs, saves the downloaded files to the path specified by the *$path*
* argument, and executes the callback function specified by the *$callback* argument for each and every request,
* as soon as the request finishes.
*
* > If the path you are downloading from refers to a file, the file's original name will be preserved but, if
* you are downloading a file generated by a script (i.e. https://foo.com/bar.php?w=1200&h=800), the downloaded
* file's name will be random generated. Refer to the downloaded file's name in the result's `info` attribute,
* in the `downloaded_filename` section - see the example below.
*
* > If you are downloading multiple files with the same name the later ones will overwrite the previous ones.
*
* 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:
*
* - `CURLINFO_HEADER_OUT` = `TRUE`
* - `CURLOPT_BINARYTRANSFER` = `TRUE`
* - `CURLOPT_HEADER` = `TRUE`
* - `CURLOPT_FILE`
*
* ...and will unset the following options:
*
* - `CURLOPT_CUSTOMREQUEST`
* - `CURLOPT_HTTPGET`
* - `CURLOPT_NOBODY`
* - `CURLOPT_POST`
* - `CURLOPT_POSTFIELDS`
*
* Multiple requests are processed asynchronously, in parallel, and the callback function is called for each and every
* request as soon as the request finishes. The number of parallel requests to be constantly processed, at all times,
* is set through the {@link threads} property. See also {@link pause_interval}.
*
* > Because requests are done asynchronously, when initiating multiple requests at once, these may not finish in
* the order in which they were initiated!
*
* <code>
* // instantiate the class
* $curl = new Zebra_cURL();
*
* // if making requests over HTTPS we need to load a CA bundle
* // so we don't get CURLE_SSL_CACERT response from cURL
* // you can get this bundle from https://curl.se/docs/caextract.html
* $curl->ssl(true, 2, 'path/to/cacert.pem');
*
* // download 2 images from 2 different websites
* // and execute a callback function for each request, as soon as it finishes
* $curl->download(array(
*
* 'https://www.somewebsite.com/images/alpha.jpg',
* 'https://www.otherwebsite.com/images/omega.jpg',
*
* // the callback function receives as argument an object with 4 properties
* // (info, header, body and response)
* ), 'destination/path/', function($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 https://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);
*
* // get the downloaded file's path
* $result->info['downloaded_filename'];
*
* // show the server's response code
* } else trigger_error('Server responded with code ' . $result->info['http_code'], E_USER_ERROR);
*
* // something went wrong
* // ($result still contains all data that could be gathered)
* } else trigger_error('cURL responded with: ' . $result->response[0], E_USER_ERROR);
*
* });
* </code>
*
* @param mixed $urls URL(s) to send the request(s) to.
*
* Can be any of the following:
*
* <code>
* // a string
* $curl->download('https://address.com/file.foo', 'path', 'callback');
*
* // an array, for multiple requests
* $curl->download(array(
* 'https://address1.com/file1.foo',
* 'https://address2.com/file2.bar',
* ), 'path', 'callback');
* </code>
*
* If {@link option() custom options} need to be set for each request, use the
* following format:
*
* <code>
* // this can also be an array of arrays, for multiple requests
* $curl->download(array(
*
* // mandatory!
* 'url' => 'https://address.com/file.foo',
*
* // optional, used to set any cURL option
* // in the same way you would set with the options() method
* 'options' => array(
* CURLOPT_USERAGENT => 'Dummy scraper 1.0',
* ),
*
* ), 'path', 'callback');
* </code>
*
* @param string $path The path to where to save the file(s) to.
*
* *If path is not pointing to a directory or the directory is not writable, the
* library will trigger an error.*
*
* @param mixed $callback (Optional) Callback function to be called as soon as the request finishes.
*
* Read full description of the argument at the {@link get} method.
*
* @return void
*/
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);
// normalize URLs
// (transforms every allowed combination to the same type of array)
$urls = $this->_prepare_urls($urls);
// iterate through the list of URLs to process
foreach ($urls as $values)
// add each URL and associated properties to the "_requests" property
$this->_requests[] = array(
'url' => $values['url'],
'path' => rtrim($path, '/\\') . '/',
// merge any custom options with the default ones
'options' =>
(isset($values['options']) ? $values['options'] : array()) +
array(
CURLINFO_HEADER_OUT => 1,
CURLOPT_BINARYTRANSFER => 1,
CURLOPT_HEADER => 0,
CURLOPT_CUSTOMREQUEST => 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(func_get_args(), 3, null, true),
);
// 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 but downloads are made from an FTP server.
*
* Downloads one or more files from an FTP server, to which the connection is made using the given *$username* and
* *$password* arguments, saves the downloaded files (with their original name) to the path specified by the *$path*
* argument, and executes the callback function specified by the *$callback* argument for each and every request,
* as soon as the 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:
*
* - `CURLINFO_HEADER_OUT` = `TRUE`
* - `CURLOPT_BINARYTRANSFER` = `TRUE`
* - `CURLOPT_HEADER` = `TRUE`
* - `CURLOPT_FILE`
*
* ...and will unset the following options:
*
* - `CURLOPT_CUSTOMREQUEST`
* - `CURLOPT_HTTPGET`
* - `CURLOPT_NOBODY`
* - `CURLOPT_POST`
* - `CURLOPT_POSTFIELDS`
*
* > If you are downloading multiple files with the same name the later ones will overwrite the previous ones.
*
* Multiple requests are processed asynchronously, in parallel, and the callback function is called for each and every
* request as soon as the request finishes. The number of parallel requests to be constantly processed, at all times,
* is set through the {@link threads} property. See also {@link pause_interval}.
*
* > Because requests are done asynchronously, when initiating multiple requests at once, these may not finish in
* the order in which they were initiated!
*
* <code>
* // instantiate the class
* $curl = new Zebra_cURL();
*
* // if making requests over HTTPS we need to load a CA bundle
* // so we don't get CURLE_SSL_CACERT response from cURL
* // you can get this bundle from https://curl.se/docs/caextract.html
* $curl->ssl(true, 2, 'path/to/cacert.pem');
*
* // connect to the FTP server using the given credential, download a file to a given location
* // and execute a callback function for each request, as soon as it finishes
* $curl->ftp_download(
*
* 'ftp://somefile.ext',
* 'destination/path',
* 'username',
* 'password',
*
* // the callback function receives as argument an object with 4 properties
* // (info, header, body and response)
* function($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 https://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 trigger_error('Server responded with code ' . $result->info['http_code'], E_USER_ERROR);
*
* // something went wrong
* // ($result still contains all data that could be gathered)
* } else trigger_error('cURL responded with: ' . $result->response[0], E_USER_ERROR);
*
* }
*
* );
* </code>
*
* @param mixed $urls URL(s) to send the request(s) to.
*
* Can be any of the following:
*
* <code>
* // a string
* $curl->ftp_download(
* 'ftp://address.com/file.foo',
* 'destination/path',
* 'username',
* 'password',
* 'callback'
* );
*
* // an array, for multiple requests
* $curl->ftp_download(array(
* 'ftp://address1.com/file1.foo',
* 'ftp://address2.com/file2.bar',
* ), 'destination/path', 'username', 'password', 'callback');
* </code>
*
* If {@link option() custom options} need to be set for each request, use the
* following format:
*
* <code>
* // this can also be an array of arrays, for multiple requests
* $curl->ftp_download(array(
*
* // mandatory!
* 'url' => 'ftp://address.com/file.foo',
*
* // optional, used to set any cURL option
* // in the same way you would set with the options() method
* 'options' => array(
* CURLOPT_USERAGENT => 'Dummy scraper 1.0',
* ),
*
* ), 'destination/path', 'username', 'password', 'callback');
* </code>
*
* Note that in all the examples above, you are downloading files from a single
* FTP server. To make requests to multiple FTP servers, set the `CURLOPT_USERPWD`
* option yourself. The *$username* and *$password* arguments will be overwritten
* by the values set like this.
*
* <code>
* $curl->ftp_download(array(
* array(
* 'url' => 'ftp://address1.com/file1.foo',
* 'options' => array(
* CURLOPT_USERPWD => 'username1:password1',
* ),
* ),
* array(
* 'url' => 'ftp://address2.com/file2.foo',
* 'options' => array(
* CURLOPT_USERPWD => 'username2:password2',
* ),
* ),
* ), 'destination/path', '', '', 'callback');
* </code>
*
* @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).
*