[8c9fcb2] | 1 | <?php |
---|
| 2 | |
---|
| 3 | /* |
---|
[357352b] | 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. |
---|
[04319fb] | 7 | * @warning Default options: does not verifying certificate, connection timeout 200 ms. |
---|
[357352b] | 8 | * @Date 2015-10-14 |
---|
[8c9fcb2] | 9 | */ |
---|
[42d268a4] | 10 | function multiRequest($data, $options=array(CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_TIMEOUT_MS => 500)) { |
---|
[8c9fcb2] | 11 | |
---|
| 12 | // array of curl handles |
---|
| 13 | $curly = array(); |
---|
[357352b] | 14 | // Data to be returned (response data and code) |
---|
[8c9fcb2] | 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; |
---|
[ba3c59d] | 28 | curl_setopt($curly[$id], CURLOPT_URL, $url); |
---|
[357352b] | 29 | // HTTP headers? |
---|
[69052958] | 30 | if (is_array($d) && !empty($d['header'])) { |
---|
[e46f7ce] | 31 | curl_setopt($curly[$id], CURLOPT_HTTPHEADER, $d['header']); |
---|
[69052958] | 32 | } else { |
---|
| 33 | curl_setopt($curly[$id], CURLOPT_HEADER, 0); |
---|
| 34 | } |
---|
[8c9fcb2] | 35 | curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1); |
---|
| 36 | |
---|
| 37 | // post? |
---|
| 38 | if (is_array($d)) { |
---|
| 39 | if (!empty($d['post'])) { |
---|
[ba3c59d] | 40 | curl_setopt($curly[$id], CURLOPT_POST, 1); |
---|
[8c9fcb2] | 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 | |
---|
[357352b] | 60 | // Get content and HTTP code, and remove handles |
---|
[8c9fcb2] | 61 | foreach($curly as $id => $c) { |
---|
[357352b] | 62 | $result[$id]['data'] = curl_multi_getcontent($c); |
---|
| 63 | $result[$id]['code'] = curl_getinfo($c, CURLINFO_HTTP_CODE); |
---|
[8c9fcb2] | 64 | curl_multi_remove_handle($mh, $c); |
---|
| 65 | } |
---|
| 66 | |
---|
| 67 | // all done |
---|
| 68 | curl_multi_close($mh); |
---|
| 69 | |
---|
| 70 | return $result; |
---|
| 71 | } |
---|
[b6ec162] | 72 | |
---|