-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCurl.php
More file actions
497 lines (426 loc) · 13.8 KB
/
Curl.php
File metadata and controls
497 lines (426 loc) · 13.8 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
<?php
/**
* Curl.php
*
* This file is part of Curl.
*
* @author Muhammet ŞAFAK <info@muhammetsafak.com.tr>
* @copyright Copyright © 2022 Muhammet ŞAFAK
* @license ./LICENSE MIT
* @version 1.0
* @link https://www.muhammetsafak.com.tr
*/
declare(strict_types=1);
namespace InitPHP\Curl;
use InitPHP\Curl\Exception\CurlException;
class Curl
{
public const SUPPORTED_HTTP_METHODS = [
'GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'
];
protected ?string $url = null;
protected ?string $userInfo = null;
protected ?string $userAgent = null;
protected ?string $referer = null;
protected string $method = 'GET';
protected array $headers = [];
protected string $version = '1.1';
protected array $options = [];
protected ?string $body = null;
protected array $uploads = [];
protected array $fields = [];
protected array $cookies = [];
protected bool $canFollow = false;
protected bool $allowRedirects = false;
protected int $maxRedirects = 3;
protected int $timeout = 0;
protected int $timeoutMS = 0;
protected array $response = [
'status' => null,
'version' => null,
'code' => null,
'body' => '',
'headers' => []
];
protected array $getInfo = [];
protected ?string $error = null;
/** @var null|resource|false */
protected $curl = null;
/** @var null|bool|string */
protected $exec = null;
public function __construct()
{
if(!\extension_loaded('curl')){
throw new CurlException('The CURL extension must be installed.');
}
$this->canFollow = (!\ini_get('safe_mode') && !\ini_get('open_basedir'));
}
public function __debugInfo()
{
return [
'url' => $this->url
];
}
public static function client(string $method, string $url): Curl
{
$client = new self();
$client->setMethod($method)
->setUrl($url);
return $client;
}
public static function get(string $method, string $url, array $headers = [], ?string $body = null, string $version = '1.1'): array
{
$curl = self::client($method, $url)
->setVersion($version);
if(!empty($headers)){
$curl->setHeaders($headers);
}
if(!empty($body)){
$curl->setBody($body);
}
if(!$curl->handler()){
return [
'error' => (!empty($curl->getError()) ? $curl->getError() : 'Something went wrong.'),
'info' => $curl->getInfo()
];
}
return $curl->getResponse();
}
public function setUrl(string $url): self
{
if(\filter_var($url, \FILTER_VALIDATE_URL) === FALSE){
throw new \InvalidArgumentException('URL address could not be verified');
}
$this->url = $url;
$parse = \parse_url($url);
$this->userInfo = $parse['user'] ?? null;
return $this;
}
public function setHeader(string $name, string $value): self
{
$this->headers[$name] = $value;
return $this;
}
public function setHeaders(array $headers): self
{
$this->headers = \array_merge($this->headers, $headers);
return $this;
}
public function setMethod(string $method = 'GET'): self
{
$method = \strtoupper($method);
if(\in_array($method, self::SUPPORTED_HTTP_METHODS, true) === FALSE){
throw new \InvalidArgumentException(('Request method can only be ' . \implode(', ', self::SUPPORTED_HTTP_METHODS)));
}
$this->method = $method;
return $this;
}
public function setBody(string $body): self
{
$this->body = $body;
return $this;
}
public function setVersion(string $httpVersion = '1.1'): self
{
$supported_version = ['1.0', '1.1'];
if(\defined('CURL_HTTP_VERSION_2_0')){
$supported_version[] = '2.0'; //libcurl v7.33 or higher
}
if(\in_array($httpVersion, $supported_version, true) === FALSE){
throw new \InvalidArgumentException(('The protocol can only be ' . \implode(', ', $supported_version)));
}
$this->version = $httpVersion;
return $this;
}
public function setUserAgent(?string $userAgent = null): self
{
$this->userAgent = $userAgent;
return $this;
}
public function setReferer(?string $referer = null): self
{
$this->referer = $referer;
return $this;
}
public function setAllowRedirect(int $maxRedirect = 3): self
{
if($maxRedirect < 0){
$maxRedirect = 0;
}
if($this->canFollow === FALSE){
throw new CurlException('"safe_mode" and "open_basedir" must be disabled in the server configuration to follow cURL redirects.');
}
$this->allowRedirects = true;
$this->maxRedirects = $maxRedirect;
return $this;
}
public function setTimeout(int $timeout = 0, bool $isMicrosecond = false): self
{
if($timeout < 0){
$timeout = 0;
}
if($isMicrosecond){
$this->timeoutMS = $timeout;
}else{
$this->timeout = $timeout;
}
return $this;
}
public function setField(string $key, string $value): self
{
$this->fields[$key] = $value;
return $this;
}
public function setFields(array $fields) : self
{
$this->fields = \array_merge($this->fields, $fields);
return $this;
}
public function setSSL(int $host = 2, int $verify = 1, ?int $version = null): self
{
$this->addCurlOption(\CURLOPT_SSL_VERIFYPEER, $verify)
->addCurlOption(\CURLOPT_SSL_VERIFYHOST, $host);
if($version !== null){
$this->addCurlOption(\CURLOPT_SSLVERSION, $version);
}
return $this;
}
public function setProxy($proxy): self
{
$this->addCurlOption(\CURLOPT_PROXY, $proxy);
return $this;
}
public function setUpload(string $name, \CURLFile $file): self
{
$this->uploads[$name] = $file;
return $this;
}
/**
* @param string $name
* @param string|int|float $value
* @return $this
*/
public function setCookie(string $name, $value): self
{
if(!\is_string($value) && !\is_numeric($value)){
throw new \InvalidArgumentException("Defined '" . $name . "' cookie value can only be string or numeric.");
}
$name = \trim($name);
$value = \trim((string)$value);
$this->cookies[$name] = $value;
return $this;
}
public function setCookies(array $cookies): self
{
foreach ($cookies as $key => $value) {
$this->setCookie((string)$key, $value);
}
return $this;
}
public function setCookieJarFile(string $filePath): self
{
if(!\is_file($filePath)){
$this->addCurlOption(\CURLOPT_COOKIEJAR, $filePath);
}else{
$this->addCurlOption(\CURLOPT_COOKIEFILE, $filePath);
}
return $this;
}
/**
* @param null|string $key
* @return null|mixed
*/
public function getResponse(?string $key = null)
{
if(empty($this->response)){
return null;
}
return ($key === null) ? $this->response : ($this->response[$key] ?? null);
}
/**
* @param string|null $key
* @return null|mixed
*/
public function getInfo(?string $key = null)
{
if(empty($this->getInfo)){
return null;
}
if($key === null){
return $this->getInfo;
}
return $this->getInfo[$key] ?? null;
}
public function getError(): ?string
{
return empty($this->error) ? null : $this->error;
}
/**
* @param string $filePath
* @return false|int
*/
public function save(string $filePath)
{
$content = $this->getResponse('body');
if (empty($content)) {
return false;
}
return @\file_put_contents($filePath, $content);
}
/**
* @param int|string $key
* @param mixed $value
* @return $this
*/
public function setOpt($key, $value): self
{
$this->options[$key] = $value;
return $this;
}
public function setOptions(array $options): self
{
$this->options = \array_merge($this->options, $options);
return $this;
}
public function handler(): bool
{
$this->curlOptionsPrepare();
$this->curl = \curl_init();
try {
if(!empty($this->options)){
\curl_setopt_array($this->curl, $this->options);
}
$this->exec = \curl_exec($this->curl);
$this->getInfo = \curl_getinfo($this->curl);
$this->error = \curl_error($this->curl);
}catch (\Exception $e) {
throw new CurlException($e->getMessage());
} finally {
\curl_setopt_array($this->curl, [
\CURLOPT_HEADERFUNCTION => null,
\CURLOPT_READFUNCTION => null,
\CURLOPT_WRITEFUNCTION => null,
\CURLOPT_PROGRESSFUNCTION => null
]);
\curl_reset($this->curl);
if (PHP_VERSION_ID < 80500) {
\curl_close($this->curl);
}
$this->curl = null;
}
return !empty($this->exec);
}
private function curlOptionsPrepare(): void
{
if(\defined('CURLOPT_PROTOCOLS')){
$this->addCurlOption(\CURLOPT_PROTOCOLS, (\CURLPROTO_HTTP | \CURLPROTO_HTTPS))
->addCurlOption(\CURLOPT_REDIR_PROTOCOLS, (\CURLPROTO_HTTP | \CURLPROTO_HTTPS));
}
$this->addCurlOption(\CURLOPT_HEADER, false)
->addCurlOption(\CURLOPT_FAILONERROR, false);
$this->addCurlOption(\CURLOPT_RETURNTRANSFER, false);
$canFollow = $this->canFollow && $this->allowRedirects;
$this->addCurlOption(\CURLOPT_FOLLOWLOCATION, $canFollow)
->addCurlOption(\CURLOPT_MAXREDIRS, $this->maxRedirects);
if($this->timeout > 0){
$this->addCurlOption(\CURLOPT_TIMEOUT, $this->timeout);
}elseif($this->timeoutMS > 0){
$this->addCurlOption(\CURLOPT_TIMEOUT_MS, $this->timeoutMS);
}
$this->addCurlOption(\CURLOPT_CUSTOMREQUEST, $this->method)
->addCurlOption(\CURLOPT_URL, $this->url)
->addCurlOption(\CURLOPT_HTTPHEADER, $this->getRequestHeaders());
if(!empty($this->userAgent)){
$this->addCurlOption(\CURLOPT_USERAGENT, $this->userAgent);
}
if(!empty($this->referer)){
$this->addCurlOption(\CURLOPT_REFERER, $this->referer);
}
if(!empty($this->cookies)){
$cookies = [];
foreach ($this->cookies as $key => $value) {
$cookies[$key] = $key . '=' . $value;
}
$this->addCurlOption(\CURLOPT_COOKIE, \implode('; ', $cookies));
}
switch ($this->version) {
case '1.0':
$version = \CURL_HTTP_VERSION_1_0;
break;
case '1.1':
$version = \CURL_HTTP_VERSION_1_1;
break;
case '2.0':
$version = \CURL_HTTP_VERSION_2_0;
break;
default:
$version = \CURL_HTTP_VERSION_1_1;
}
$this->addCurlOption(\CURLOPT_HTTP_VERSION, $version);
if(!empty($this->userInfo)){
$this->addCurlOption(\CURLOPT_USERPWD, $this->userInfo);
}
switch ($this->method) {
case 'HEAD':
$this->addCurlOption(\CURLOPT_NOBODY, true);
break;
case 'GET':
$this->addCurlOption(\CURLOPT_HTTPGET, true);
break;
}
if(!empty($this->uploads)){
$this->fields = \array_merge($this->fields, $this->uploads);
}
if(!empty($this->fields)){
$this->addCurlOption(\CURLOPT_POST, true)
->addCurlOption(\CURLOPT_POSTFIELDS, $this->fields);
}
if(!empty($this->body)){
$this->addCurlOption(\CURLOPT_POSTFIELDS, $this->body);
}
$this->addCurlOption(\CURLOPT_HEADERFUNCTION, function ($ch, $data) {
$str = \trim($data);
if(!empty($str)){
$lowercase = \strtolower($str);
if(\strpos($lowercase, 'http/') === 0){
$this->response['status'] = $str;
if(\preg_match("/http\/([\.0-2]+) ([\d]+).?/i", $lowercase, $matches)){
$this->response['version'] = $matches[1];
$this->response['code'] = (int)$matches[2];
}
}else{
$this->response['headers'][] = $str;
}
}
return \strlen($data);
});
$this->addCurlOption(\CURLOPT_WRITEFUNCTION, function ($ch, $data) {
$this->response['body'] .= $data;
return \strlen($data);
});
}
private function addCurlOption($key, $value): self
{
if(!isset($this->options[$key])){
$this->options[$key] = $value;
}
return $this;
}
private function getRequestHeaders(): array
{
if(empty($this->headers)){
return [];
}
$headers = [];
foreach ($this->headers as $key => $values){
if(!\is_array($values)){
$headers[] = \sprintf('%s: %s', $key, $values);
}else{
foreach($values as $value){
$headers[] = \sprintf('%s: %s', $key, $value);
}
}
}
return $headers;
}
}