1 | <?php |
---|
2 | |
---|
3 | /* |
---|
4 | * @function multiRequest. |
---|
5 | * @param URLs array (may include header and POST data), cURL options array. |
---|
6 | * @return Array of arrays with JSON requests and response codes. |
---|
7 | * @warning Default options: does not verifying certificate, connection timeout 200 ms. |
---|
8 | * @Date 2015-10-14 |
---|
9 | */ |
---|
10 | function multiRequest($data, $options=array(CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_TIMEOUT_MS => 500)) { |
---|
11 | |
---|
12 | // array of curl handles |
---|
13 | $curly = array(); |
---|
14 | // Data to be returned (response data and code) |
---|
15 | $result = array(); |
---|
16 | |
---|
17 | // multi handle |
---|
18 | $mh = curl_multi_init(); |
---|
19 | |
---|
20 | // loop through $data and create curl handles |
---|
21 | // then add them to the multi-handle |
---|
22 | foreach ($data as $id => $d) { |
---|
23 | |
---|
24 | |
---|
25 | $curly[$id] = curl_init(); |
---|
26 | |
---|
27 | $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d; |
---|
28 | curl_setopt($curly[$id], CURLOPT_URL, $url); |
---|
29 | // HTTP headers? |
---|
30 | if (is_array($d) && !empty($d['header'])) { |
---|
31 | curl_setopt($curly[$id], CURLOPT_HTTPHEADER, $d['header']); |
---|
32 | } else { |
---|
33 | curl_setopt($curly[$id], CURLOPT_HEADER, 0); |
---|
34 | } |
---|
35 | curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1); |
---|
36 | |
---|
37 | // post? |
---|
38 | if (is_array($d)) { |
---|
39 | if (!empty($d['post'])) { |
---|
40 | curl_setopt($curly[$id], CURLOPT_POST, 1); |
---|
41 | curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']); |
---|
42 | } |
---|
43 | } |
---|
44 | |
---|
45 | // extra options? |
---|
46 | if (!empty($options)) { |
---|
47 | curl_setopt_array($curly[$id], $options); |
---|
48 | } |
---|
49 | |
---|
50 | curl_multi_add_handle($mh, $curly[$id]); |
---|
51 | } |
---|
52 | |
---|
53 | // execute the handles |
---|
54 | $running = null; |
---|
55 | do { |
---|
56 | curl_multi_exec($mh, $running); |
---|
57 | } while($running > 0); |
---|
58 | |
---|
59 | |
---|
60 | // Get content and HTTP code, and remove handles |
---|
61 | foreach($curly as $id => $c) { |
---|
62 | $result[$id]['data'] = curl_multi_getcontent($c); |
---|
63 | $result[$id]['code'] = curl_getinfo($c, CURLINFO_HTTP_CODE); |
---|
64 | curl_multi_remove_handle($mh, $c); |
---|
65 | } |
---|
66 | |
---|
67 | // all done |
---|
68 | curl_multi_close($mh); |
---|
69 | |
---|
70 | return $result; |
---|
71 | } |
---|
72 | ?> |
---|