How to Send Simultaneous cURL Request using curl_multi_exec

  21686 views   1 year ago PHP

In this article, i will share with you how to send simultaneous cURL requests in PHP using the curl_multi_exec() function with example. you all use cURL in PHP many times to call any third-party API in your application. but many developers still not know how to make simultaneous cURL requests make in PHP using the curl_multi_exec() function. when we need more than one request call at the same time then curl_multi_exec() is better for the reduce our execution time in an application.

By using curl_multi_exec, We can execute all these requests in parallel, and we will only be limited by the slowest request.

Example :

// array of curl handles
$multiCurl = array();
// data to be returned
$result = array();
// multi handle
$mh = curl_multi_init();
foreach ($ids as $i => $id) {
  // URL from which data will be fetched
  $fetchURL = ''.$id;
  $multiCurl[$i] = curl_init();
  curl_setopt($multiCurl[$i], CURLOPT_URL,$fetchURL);
  curl_setopt($multiCurl[$i], CURLOPT_HEADER,0);
  curl_setopt($multiCurl[$i], CURLOPT_RETURNTRANSFER,1);
  curl_multi_add_handle($mh, $multiCurl[$i]);
do {
} while($index > 0);
// get content and remove handles
foreach($multiCurl as $k => $ch) {
  $result[$k] = curl_multi_getcontent($ch);
  curl_multi_remove_handle($mh, $ch);
// close

Output :

$result[0] => {"id1":{"tag":"laravel","category":...
$result[1] => {"id2":{"tag":"python","category":...

i hope you like this solution.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]