-
-
Save Hadryan/fb8687b84ce8c742cb490cf96132ebd9 to your computer and use it in GitHub Desktop.
multiple parallel asynchronous requests on php
This file contains 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 | |
/** | |
* PHP7 OF GTFO | |
*/ | |
function request_async(array $urls, callable $callback){ | |
$multiHandle = curl_multi_init(); | |
$handles = []; | |
foreach($urls as $key => $url){ | |
$ch = curl_init($url); | |
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); | |
curl_multi_add_handle($multiHandle,$ch); | |
$handles[$key] = $ch; | |
} | |
$running = true; | |
while($running) curl_multi_exec($multiHandle, $running); | |
$result = []; | |
foreach($handles as $key => $handle){ | |
$result[$key] = curl_getinfo($handle); | |
$result[$key]['data'] = curl_multi_getcontent($handle); | |
curl_multi_remove_handle($multiHandle, $handle); | |
} | |
curl_multi_close($multiHandle); | |
$callback($result); | |
} | |
$urls=[]; | |
for($i=0;$i<1;$i++){ | |
$urls[]='localhost/async/sleep.php'; | |
} | |
request_async($urls,function($response){ | |
var_dump($response); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment