Created
July 24, 2015 17:38
-
-
Save nimmneun/ffdcf25c07ae95cc126a to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Retrieves data and curl connection info for an array of one or more urls | |
* using curl_multi_*. Input order & array key equal output order & array key. | |
* Returns 2-dimensional array containing url data & curl info. | |
* @param array $urls | |
* @return array $res | |
*/ | |
function multicurl($urls) { | |
// The curl multi handle. | |
$mh = curl_multi_init(); | |
// Array of curl handles. | |
$chs = array(); | |
// Result array which will be returned. | |
$res = array(); | |
// Create a curl handle for each url and add it to the $mh. | |
foreach ($urls as $key => $url) { | |
$chs[$key] = curl_init(); | |
curl_setopt($chs[$key], CURLOPT_URL, $url); | |
curl_setopt($chs[$key], CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($chs[$key], CURLOPT_FOLLOWLOCATION, 1); | |
curl_multi_add_handle($mh, $chs[$key]); | |
} | |
// Loop through $mh while there are active connections, | |
// but put to sleep so we don't eat up too much unnecessary cpu power. | |
$active = null; | |
do { | |
usleep(10000); | |
curl_multi_exec($mh, $active); | |
} while ($active > 0); | |
// Store url contents and connection info into result array. | |
foreach ($chs as $key => $ch) { | |
$res[$key]['data'] = curl_multi_getcontent($ch); | |
$res[$key]['info'] = curl_getinfo($ch); | |
curl_multi_remove_handle($mh, $ch); | |
} | |
curl_multi_close($mh); | |
return $res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment