1
|
|
|
<?php |
2
|
|
|
namespace Blixter\Utilities; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* |
6
|
|
|
* Model for Curl |
7
|
|
|
* |
8
|
|
|
* @SuppressWarnings(PHPMD.ShortVariable) |
9
|
|
|
*/ |
10
|
|
|
class CurlModel |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Curl to given url and return an json-response. |
14
|
|
|
* |
15
|
|
|
* @param string $url as an url to curl |
16
|
|
|
* @param bool $json decode response to json if true, Default is false. |
17
|
|
|
* |
18
|
|
|
* @return $response |
|
|
|
|
19
|
|
|
*/ |
20
|
9 |
|
public function curl($url, $json = false) |
21
|
|
|
{ |
22
|
|
|
// init curl handler and set url |
23
|
9 |
|
$ch = curl_init($url); |
24
|
|
|
|
25
|
|
|
// Return the response, if fail, print the response |
26
|
9 |
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
|
|
|
|
27
|
|
|
|
28
|
|
|
// Store the returned data |
29
|
9 |
|
$response = curl_exec($ch); |
|
|
|
|
30
|
|
|
|
31
|
|
|
// Close the curl handler |
32
|
9 |
|
curl_close($ch); |
|
|
|
|
33
|
|
|
|
34
|
|
|
// If $json === true |
35
|
9 |
|
if ($json) { |
36
|
|
|
// Decode to JSON |
37
|
9 |
|
$response = json_decode($response, true); |
38
|
|
|
} |
39
|
|
|
|
40
|
9 |
|
return $response; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Curl to given urls and return an response. |
45
|
|
|
* |
46
|
|
|
* @param array $urls as an array with urls to curl |
47
|
|
|
* @param bool $json decode response to json if true, Default is false. |
48
|
|
|
* |
49
|
|
|
* @return array $response with the responses |
50
|
|
|
*/ |
51
|
4 |
|
public function multiCurl($urls, $json = false) |
52
|
|
|
{ |
53
|
|
|
$options = [ |
54
|
4 |
|
CURLOPT_RETURNTRANSFER => true, |
55
|
|
|
]; |
56
|
|
|
|
57
|
|
|
// Add the curl handlers. |
58
|
|
|
// Init the multi curl |
59
|
4 |
|
$mh = curl_multi_init(); |
60
|
4 |
|
$chAll = []; |
61
|
4 |
|
foreach ((array) $urls as $url) { |
62
|
4 |
|
$ch = curl_init($url); |
63
|
4 |
|
curl_setopt_array($ch, $options); |
|
|
|
|
64
|
4 |
|
curl_multi_add_handle($mh, $ch); |
|
|
|
|
65
|
4 |
|
$chAll[] = $ch; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
// Execute the multi curls |
69
|
4 |
|
$running = null; |
70
|
|
|
do { |
71
|
4 |
|
curl_multi_exec($mh, $running); |
72
|
4 |
|
} while ($running); |
73
|
|
|
|
74
|
|
|
// Close the handles |
75
|
4 |
|
foreach ($chAll as $ch) { |
76
|
4 |
|
curl_multi_remove_handle($mh, $ch); |
77
|
|
|
} |
78
|
4 |
|
curl_multi_close($mh); |
79
|
|
|
|
80
|
|
|
// The requests are done and the result stored in $response |
81
|
4 |
|
$response = []; |
82
|
4 |
|
foreach ($chAll as $ch) { |
83
|
4 |
|
$data = curl_multi_getcontent($ch); |
84
|
4 |
|
if ($json) { |
85
|
|
|
// Decode to JSON |
86
|
3 |
|
$response[] = json_decode($data, true); |
87
|
|
|
|
88
|
|
|
} else { |
89
|
4 |
|
$response[] = $data; |
90
|
|
|
} |
91
|
|
|
} |
92
|
4 |
|
return $response; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|