forked from onassar/PHP-Curler
/
Curler.php
928 lines (846 loc) · 27.1 KB
/
Curler.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
<?php
namespace Muraveiko\PhpCurler;
// dependecy check
if (!in_array('curl', get_loaded_extensions())) {
throw new Exception('cURL extension needs to be installed.');
}
/**
* Curler
*
* Makes cURL requests (GET, HEAD and POST) to a URI.
*
* @link https://github.com/onassar/PHP-Curler
* @author Oliver Nassar <onassar@gmail.com>
*/
class Curler
{
/**
* _acceptableMimeTypes
*
* Array of acceptable mime types that ought to result in a successful
* cURL request.
*
* @var array (default: array())
* @access protected
*/
protected $_acceptableMimeTypes = array();
/**
* _cookieStoragePath
*
* Path to the cookie file that should be used for temporary storage of
* cookies that are sent back by a curl. This is only used to ensure
* servers that require cookie saving to properly respond to a request.
*
* @var false|string (default: false)
* @access protected
*/
protected $_cookieStoragePath = false;
/**
* _curlErrors
*
* @var array (default: array())
* @access protected
*/
protected $_curlErrors = array();
/**
* _dynamicResponse
*
* Variable used to store content during a get request to ensure
* filesize limits aren't reached.
*
* @var string (default: '')
* @access protected
*/
protected $_dynamicResponse = '';
/**
* _error
*
* Array containing details of a possible error.
*
* @var false|array (default: false)
* @access protected
*/
protected $_error = false;
/**
* _headers
*
* Array containing the request headers that will be sent with the curl.
*
* @var array (default: array())
* @access protected
*/
protected $_headers = array();
/**
* _headInfo
*
* @var array
* @access protected
*/
protected $_headInfo;
/**
* _info
*
* Storage of the info that was returned by the GET and HEAD calls
* (since a GET is always preceeded by a HEAD).
*
* @var array
* @access protected
*/
protected $_info;
/**
* _mimes
*
* @var array (default: array())
* @access protected
*/
protected $_mimes = array();
/**
* _options
*
* @var array
* @access protected
*/
protected $_options = array(
'authCredentials' => array(),
'maxFilesize' => 1048576,// 1 * 1024 * 1024
'maxRedirects' => 10,
'timeout' => 5000,
'userAgent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12',
'validHTTPCodes' => array(200),
'validMimeTypes' => 'webpages'
);
/**
* _response
*
* @var String
* @access protected
*/
protected $_response;
/**
* _curlOptions
*
* Array of curl options
*
* @var array
* @access protected
*/
protected $_curlOptions = array();
/**
* __construct
*
* @access public
* @param array $options {
* @var array $authCredentials [ 'username' => '' , 'password'=>'']
* @var int $maxFilesize
* @var int $maxRedirects
* @var int $timeout
* @var string $userAgent
* @var int[] $validHTTPCodes
* @var string $validMimeTypes
* }
*/
public function __construct($options = array())
{
// Cookie path
$info = pathinfo(__DIR__);
$parent = ($info['dirname']);
$this->_cookieStoragePath = ($parent) . '/tmp/cookies.txt';
// Extend options
$this->_options = array_merge($this->_options, $options);
$this->_loadMimeMap();
$this->_loadCurlErrorMap();
$this->setMime($this->_options['validMimeTypes']);
$this->setHeaders(array(
'Connection' => 'keep-alive',
'Accept-Language' => 'en-us,en;q=0.5'
));
// Set default curl options
$this->setCurlOptions(array(
'CURLOPT_SSL_VERIFYPEER' => false,
'CURLOPT_SSL_VERIFYHOST' => 2,
'CURLOPT_FOLLOWLOCATION' => true
// 'CURLOPT_MAXREDIRS' => $this->_options['maxRedirects']
));
}
/**
* _close
*
* @access protected
* @param resource $resource
* @return void
*/
protected function _close($resource)
{
curl_close($resource);
}
/**
* _getHeaders
*
* Parses and returns the headers for the curl request.
*
* @access protected
* @return array headers formatted to be correctly formed for an HTTP request
*/
protected function _getHeaders()
{
$formatted = array();
foreach ($this->_headers as $name => $value) {
array_push($formatted, ($name) . ': ' . ($value));
}
return $formatted;
}
/**
* _getResource
*
* Creates a curl resource, set's it up, and returns it's reference.
*
* @access protected
* @param string $url
* @param boolean $head. (default: false) whether or not this is a HEAD
* request, in which case no response-body is returned
* @return Resource curl resource reference
*/
protected function _getResource($url, $head = false)
{
// ensure cookie is writable by attempting to open it up
$this->_openCookie();
// init call, headers, user agent
$options = $this->_options;
$resource = curl_init($url);
curl_setopt($resource, CURLOPT_HTTPHEADER, $this->_getHeaders());
curl_setopt($resource, CURLOPT_HEADER, false);
curl_setopt($resource, CURLOPT_USERAGENT, $options['userAgent']);
curl_setopt($resource, CURLOPT_ENCODING, 'gzip,deflate');
/**
* HTTP Authentication
*
*/
if (empty($this->_options['authCredentials']) === false) {
$username = $this->_options['authCredentials']['username'];
$password = $this->_options['authCredentials']['password'];
$token = ($username) . ':' . ($password);
curl_setopt($resource, CURLOPT_USERPWD, $token);
}
/**
* Cookie file / jar
*
*/
$cookieStoragePath = $this->_cookieStoragePath;
curl_setopt($resource, CURLOPT_COOKIEFILE, $cookieStoragePath);
curl_setopt($resource, CURLOPT_COOKIEJAR, $cookieStoragePath);
/**
* Timeout
*
*/
$timeout = $options['timeout'];
curl_setopt($resource, CURLOPT_CONNECTTIMEOUT_MS, $timeout);
curl_setopt($resource, CURLOPT_TIMEOUT_MS, $timeout);
/**
* SSL Security Setitngs
*
*/
$verifyPeer = $this->_curlOptions['CURLOPT_SSL_VERIFYPEER'];
$verifyHost = $this->_curlOptions['CURLOPT_SSL_VERIFYHOST'];
curl_setopt($resource, CURLOPT_SSL_VERIFYPEER, $verifyPeer);
curl_setopt($resource, CURLOPT_SSL_VERIFYHOST, $verifyHost);
curl_setopt($resource, CURLOPT_FRESH_CONNECT, true);
/**
* Other Security Setitngs
*
*/
$followLocation = $this->_curlOptions['CURLOPT_FOLLOWLOCATION'];
$maxRedirects = (int) $this->_options['maxRedirects'];
curl_setopt($resource, CURLOPT_RETURNTRANSFER, true);
curl_setopt($resource, CURLOPT_FOLLOWLOCATION, $followLocation);
curl_setopt($resource, CURLOPT_MAXREDIRS, $maxRedirects);
curl_setopt($resource, CURLOPT_NOBODY, $head === true);
// Done
return $resource;
}
/**
* _loadCurlErrorMap
*
* @access protected
* @return void
*/
protected function _loadCurlErrorMap()
{
$info = pathinfo(__DIR__);
$parent = ($info['dirname']);
$path = ($parent) . '/maps/curlErrors.json';
$content = file_get_contents($path);
$this->_curlErrors = json_decode($content, true);
}
/**
* _loadMimeMap
*
* @access protected
* @return void
*/
protected function _loadMimeMap()
{
$info = pathinfo(__DIR__);
$parent = ($info['dirname']);
$path = ($parent) . '/maps/mimes.json';
$content = file_get_contents($path);
$this->_mimes = json_decode($content, true);
}
/**
* _openCookie
*
* Helper method to either ensure that the cookie file that exists can
* be written to, or else that the directory that ought to contain the
* cookie file is writable. If it's the second case, and it passes, then
* a cookie file is written to the proper path.
*
* @access protected
* @return void
* @throws Exception
*/
protected function _openCookie()
{
// ensure file is writable
if (file_exists($this->_cookieStoragePath) === true) {
if (! is_writeable($this->_cookieStoragePath)) {
throw new Exception(
'File *' . ($this->_cookieStoragePath) . '* must be ' .
'writable for cookie storage.'
);
}
}
// ensure file directory is writable
else {
$dir = dirname($this->_cookieStoragePath);
if (is_writable($dir) === false) {
throw new Exception(
'Path *' . ($dir) . '* must be writable for cookie ' .
'storage.'
);
}
// open file
$resource = fopen($this->_cookieStoragePath, 'w');
fclose($resource);
}
}
/**
* _valid
*
* Ensures that a request is valid, based on the http code, mime type
* and content length returned.
*
* @access protected
* @return Boolean whether or not the request is valid to be processed
*/
protected function _valid()
{
/**
* HTTP Status Code
*
*/
$validHTTPCodes = $this->_options['validHTTPCodes'];
if (in_array($this->_headInfo['http_code'], $validHTTPCodes) === false) {
$this->_error = array(
'code' => 'CUSTOM_HTTPSTATUSCODE',
'message' => ($this->_headInfo['http_code']) .
' status code received while trying to retrieve ' .
($this->_headInfo['url'])
);
return false;
}
/**
* Mime
*
*/
$mimes = $this->getMimes();
$pieces = explode(';', $this->_headInfo['content_type']);
$mime = current($pieces);
if (in_array($mime, $mimes) === false) {
$mime = current(explode(';', $this->_headInfo['content_type']));
$accepted = implode(', ', $this->getMimes());
$this->_error = array(
'code' => 'CUSTOM_MIME',
'message' => 'Mime-type requirement not met. Resource is ' .
($mime) . '. You were hoping for one of: ' .
($accepted) . '.',
);
return false;
}
/**
* Filesize
*
*/
$maxFilesize = (int) $this->_options['maxFilesize'];
$contentLength = (int) $this->_headInfo['download_content_length'];
if($contentLength > $maxFilesize) {
$this->_error = array(
'code' => 'CUSTOM_FILESIZE',
'message' => 'File size limit reached. Limit was set to ' .
($maxFilesize) . '. Resource is ' . ($contentLength)
);
return false;
}
// Done
return true;
}
/**
* addMime
*
* Adds a specific mime type to the acceptable range for a
* return/response.
*
* @access public
* @param string $mime
* @return void
*/
public function addMime($mime)
{
$this->_acceptableMimeTypes[] = $mime;
}
/**
* addMimes
*
* Adds passed in mime types to the array tracking which are acceptable
* to be returned.
*
* @access public
* @return void
*/
public function addMimes()
{
$args = func_get_args();
foreach ($args as $mime) {
$this->addMime($mime);
}
}
/**
* get
*
* Returns the actual content (string), or else false if the request
* failed.
*
* @access public
* @param string $url
* @return string|false
*/
public function get($url)
{
// for reuse
$this->_dynamicResponse = '';
/**
* Content Type Header
*
*/
$mimes = implode(',', $this->getMimes());
$this->setHeader('Accept', $mimes);
/**
* Resource and retrieval
*
*/
$resource = $this->_getResource($url);
$callback = array($this, 'writeCallback');
curl_setopt($resource, CURLOPT_WRITEFUNCTION, $callback);
/**
* Execute and check for filesize limit
*
*/
try {
curl_exec($resource);
} catch (Exception $exception) {
$this->_error = array(
'code' => 'CUSTOM_FILESIZE',
'message' => $exception->getMessage()
);
return false;
}
$this->_response = $this->_dynamicResponse;
$this->_headInfo = $this->_info = curl_getinfo($resource);
/**
* Native cURL Error
*
*/
if ((int) curl_errno($resource) !== 0) {
$code = $this->_curlErrors[(int) curl_errno($resource)];
$this->_error = array(
'code' => $code,
'message' => curl_error($resource)
);
}
// Done
$this->_close($resource);
if ($this->_error !== false) {
return false;
}
if ($this->_valid() === false) {
return false;
}
return $this->_response;
}
/**
* getCharset
*
* Requires $this->get to be called before being called.
*
* @access public
* @return string|false
*/
public function getCharset()
{
$headerCharset = $this->getHeaderCharset();
if ($headerCharset !== false) {
return $headerCharset;
}
return $this->getContentCharset();
}
/**
* getContentCharset
*
* @note The `url` value being used from the curler info is valid to
* use since it is the redirect url. For example, if a bit.ly
* link is specified, the `url` value being used below is not
* bit.ly, but rather whatever site it's being redirect to.
* @access public
* @return string|false
* @throws Exception
*/
public function getContentCharset()
{
// dependency check
if (class_exists('MetaParser') === false) {
throw new Exception(
'*MetaParser* class required. Please see ' .
'https://github.com/onassar/PHP-MetaParser'
);
}
// instantiate parser to get access to content's provided charset
$info = $this->getInfo();
$parser = new MetaParser($this->_response, $info['url']);
return $parser->getCharset();
}
/**
* getError return array['code'=>,'message'=>]
*
* @access public
* @return false|array
*/
public function getError()
{
return $this->_error;
}
/**
* getHeaderCharset
*
* @access public
* @return string|false
*/
public function getHeaderCharset()
{
$info = $this->getInfo();
$contentType = $info['content_type'];
$pattern = '#charset=([a-zA-Z0-9-]+)#';
preg_match($pattern, $contentType, $matches);
if (isset($matches[1]) === true) {
$charset = array_pop($matches);
$charset = trim($charset);
$charset = strtolower($charset);
if ($charset === 'utf8') {
return 'utf-8';
}
return $charset;
}
return false;
}
/**
* getInfo
*
* Grabs the previously stored info for the curl call.
*
* @access public
* @return array
*/
public function getInfo()
{
return $this->_info;
}
/**
* getHeadInfo
*
* @access public
* @return array
*/
public function getHeadInfo()
{
return $this->_headInfo;
}
/**
* getMimes
*
* Maps the mime types specified and returns them for the curl requests.
*
* @access public
* @return array mime
*/
public function getMimes()
{
$mimes = array();
foreach ($this->_mimes as $mime => $buckets) {
$intersection = array_intersect(
$this->_acceptableMimeTypes,
$buckets
);
if (in_array($mime, $this->_acceptableMimeTypes) === true) {
array_push($mimes, $mime);
} elseif (empty($intersection) === false) {
$mimes = array_merge($mimes, (array) $mime);
}
}
return array_unique($mimes);
}
/**
* head
*
* Make a HEAD call to the passed in URI. Note that this call can fail
* in two ways:
* 1. Timeout is reached
* 2. Max redirects is reached
*
* @access public
* @param string $uri
* @return void
*/
public function head($uri)
{
$this->setHeader('Accept', '*/*');
$resource = $this->_getResource($uri, true);
curl_exec($resource);
$this->_headInfo = curl_getinfo($resource);
if ((int) curl_errno($resource) !== 0) {
$code = $this->_curlErrors[(int) curl_errno($resource)];
$this->_error = array(
'code' => $code,
'message' => curl_error($resource)
);
}
$this->_close($resource);
}
/**
* getResponse
*
* Grabs the previously stored response.
*
* @access public
* @return string
*/
public function getResponse()
{
return $this->_response;
}
/**
* post
*
* @access public
* @param string $url
* @param array $data
* @param boolean $buildQuery (default: true)
* @return array|false
*/
public function post($url, array $data = array(), $buildQuery = true)
{
/**
* Content Type Header
*
*/
$mimes = implode(',', $this->getMimes());
$this->setHeader('Accept', $mimes);
$resource = $this->_getResource($url);
// Encoding and setting of data
curl_setopt($resource, CURLOPT_POST, true);
if ($buildQuery === true) {
$data = http_build_query($data);
}
curl_setopt($resource, CURLOPT_POSTFIELDS, $data);
// make the GET call, storing the response; store the info
$this->_response = curl_exec($resource);
$this->_headInfo = $this->_info = curl_getinfo($resource);
/**
* Native cURL Error
*
*/
if ((int) curl_errno($resource) !== 0) {
$code = $this->_curlErrors[(int) curl_errno($resource)];
$this->_error = array(
'code' => $code,
'message' => curl_error($resource)
);
}
// Done
$this->_close($resource);
if ($this->_error !== false) {
return false;
}
if ($this->_valid() === false) {
return false;
}
return $this->_response;
}
/**
* xhr with request payload
*
* POSTing JSON Data WITH PHP cURL
*
* @param string $url
* @param string $data
* @param null|array $header
* @return bool|mixed|String
*/
public function ajax($url, $data,$header=null){
/**
* Content Type Header
*
*/
if(!is_null($header) && is_array($header)){
foreach ($header as $hn=>$hv){
$this->setHeader($hn, $hv);
}
}else{
$mimes = implode(',', $this->getMimes());
$this->setHeader('Accept', $mimes);
}
$resource = $this->_getResource($url);
// Encoding and setting of data
curl_setopt($resource, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($resource, CURLOPT_POSTFIELDS, $data);
// make the GET call, storing the response; store the info
$this->_response = curl_exec($resource);
$this->_headInfo = $this->_info = curl_getinfo($resource);
/**
* Native cURL Error
*
*/
if ((int) curl_errno($resource) !== 0) {
$code = $this->_curlErrors[(int) curl_errno($resource)];
$this->_error = array(
'code' => $code,
'message' => curl_error($resource)
);
}
// Done
$this->_close($resource);
if ($this->_error !== false) {
return false;
}
if ($this->_valid() === false) {
return false;
}
return $this->_response;
}
/**
* setCurlOptions
*
* @access public
* @param array $options
* @return void
*/
public function setCurlOptions(array $options)
{
foreach ($options as $key => $value) {
$this->_curlOptions[$key] = $value;
}
}
/**
* setHeader
*
* Sets a header for the request being made.
*
* @access public
* @param string $key
* @param string $value
* @return void
*/
public function setHeader($key, $value)
{
$this->_headers[$key] = $value;
}
/**
* setHeaders
*
* Sets a group of headers at once, for the request.
*
* @access public
* @param array $headers
* @return void
*/
public function setHeaders(array $headers)
{
foreach ($headers as $key => $value) {
$this->setHeader($key, $value);
}
}
/**
* setMime
*
* Proxy for setMimes.
*
* @access public
* @param string $mime
* @return void
*/
public function setMime($mime)
{
$this->setMimes($mime);
}
/**
* setMimes
*
* Stores which mime types can be accepted in the request.
*
* @notes if false specified (such as setMime(false) or
* setMimes(false)), then no mimes are set as being allowed (eg.
* good for clearing out any previously set acceptable
* mime-types)
* @access public
* @return void
*/
public function setMimes()
{
$args = func_get_args();
$this->_acceptableMimeTypes = array();
if (in_array(false, $args) === false) {
$this->_acceptableMimeTypes = $args;
}
}
/**
* setCookieStoragePath
*
* Set path to file for curl to store cookies. File must be writable.
*
* @param string $path
* @return void
*/
public function setCookieStoragePath($path)
{
$this->_cookieStoragePath = $path;
}
/**
* writeCallback
*
* Helper method to ensure that the filesize limt is not reached. Needs
* to return the number of bytes written, otherwise the transfer will
* fail.
*
* @access public
* @param Object $resource
* @param string $data
* @return integer
*
* @throws Exception
*/
public function writeCallback($resource, $data)
{
$this->_dynamicResponse .= $data;
$maxFilesize = $this->_options['maxFilesize'];
if (strlen($this->_dynamicResponse) > $maxFilesize) {
throw new Exception('Size exceeded', 1);
}
return strlen($data);
}
}