Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

php curl async callback

function process_multi_requests($urls, $callback){
      $handle = curl_multi_init();

      foreach ($urls as $url) {
          $ch = curl_init($url);
          curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => TRUE));
          curl_multi_add_handle($handle, $ch);
      }

      do {
          $mrc = curl_multi_exec($handle, $active);
          if ($state = curl_multi_info_read($handle)) {
              $info = curl_getinfo($state['handle']);
              $callback(curl_multi_getcontent($state['handle']), $info);
              curl_multi_remove_handle($handle, $state['handle']);
          }

      } while ($mrc == CURLM_CALL_MULTI_PERFORM || $active);

    curl_multi_close($handle);
} 

//usage example
$urls=array(
      "http://127.0.0.1/url1.php",
      "http://127.0.0.1/url2.php",
      "http://127.0.0.1/url3.php",
);

$GLOBALS['my_results']=[];
process_multi_requests($urls,function($result){  
 	$GLOBALS['my_results'][]=$result;
  	echo $result."
";//called when the singe request is done
});
//this runs after all requests are done
print_r($GLOBALS['my_results']);//will contain all the results
 
PREVIOUS NEXT
Tagged: #php #curl #async #callback
ADD COMMENT
Topic
Name
4+1 =