Last active
May 13, 2017 19:46
-
-
Save uchm4n/54019f3ff35d4ddce5b8f13bc693b80f to your computer and use it in GitHub Desktop.
Curl Multi Request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Usage | |
| // Get Request | |
| // pool(['url1',''url2','url3']) | |
| // | |
| // Post Request | |
| // $data[0]['url'] = 'endpoint1'; | |
| // $data[0]['post'] = []; | |
| // $data[0]['post']['param1'] = ['paramValue1']; | |
| // $data[0]['post']['param2'] = ['paramValue2']; | |
| // | |
| // $data[1]['url'] = 'endpoint2'; | |
| // $data[2]['post'] = []; | |
| // $data[1]['post']['param1'] = ['paramValue1']; | |
| // $data[1]['post']['param2'] = ['paramValue2']; | |
| // | |
| // pool($data); | |
| function pool($urls, $options = array()) { | |
| $curly = array(); | |
| $result = array(); | |
| $mh = curl_multi_init(); | |
| foreach ($urls as $id => $d) { | |
| $curly[$id] = curl_init(); | |
| $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d; | |
| curl_setopt($curly[$id], CURLOPT_URL, $url); | |
| curl_setopt($curly[$id], CURLOPT_HEADER, 0); | |
| curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1); | |
| // post | |
| if (is_array($d)) { | |
| if (!empty($d['post'])) { | |
| curl_setopt($curly[$id], CURLOPT_POST, 1); | |
| curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']); | |
| } | |
| } | |
| // extra options | |
| if (!empty($options)) { | |
| curl_setopt_array($curly[$id], $options); | |
| } | |
| curl_multi_add_handle($mh, $curly[$id]); | |
| } | |
| // execute the handles | |
| $running = null; | |
| do { | |
| curl_multi_exec($mh, $running); | |
| } while($running > 0); | |
| // get content and remove handles | |
| foreach($curly as $id => $c) { | |
| $result[$id] = curl_multi_getcontent($c); | |
| curl_multi_remove_handle($mh, $c); | |
| } | |
| // all done | |
| curl_multi_close($mh); | |
| return $result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment