PHP Using multi_curl to make multiple POST requests


Sometimes we need to make a lot of POST requests to one or many different endpoints. To deal with this scenario, we can use multi_curl.

First of all, we create how many requests as needed exactly in the same way of the simple example and put them in an array.

We use the curl_multi_init and add each handle to it.

In this example, we are using 2 different endpoints:

//array of data to POST
$request_contents = array();
//array of URLs
$urls = array();
//array of cURL handles
$chs = array();

//first POST content
$request_contents[] = [
    'a' => 'apple',
    'b' => 'banana'
//second POST content
$request_contents[] = [
    'a' => 'fish',
    'b' => 'shrimp'
//set the urls
$urls[] = '';
$urls[] = '';

//create the array of cURL handles and add to a multi_curl
$mh = curl_multi_init();
foreach ($urls as $key => $url) {
    $chs[$key] = curl_init($url);
    curl_setopt($chs[$key], CURLOPT_RETURNTRANSFER, true);
    curl_setopt($chs[$key], CURLOPT_POST, true);
    curl_setopt($chs[$key], CURLOPT_POSTFIELDS, $request_contents[$key]);

    curl_multi_add_handle($mh, $chs[$key]);

Then, we use curl_multi_exec to send the requests

//running the requests
$running = null;
do {
  curl_multi_exec($mh, $running);
} while ($running);

//getting the responses
foreach(array_keys($chs) as $key){
    $error = curl_error($chs[$key]);
    $last_effective_URL = curl_getinfo($chs[$key], CURLINFO_EFFECTIVE_URL);
    $time = curl_getinfo($chs[$key], CURLINFO_TOTAL_TIME);
    $response = curl_multi_getcontent($chs[$key]);  // get results
    if (!empty($error)) {
      echo "The request $key return a error: $error" . "\n";
    else {
      echo "The request to '$last_effective_URL' returned '$response' in $time seconds." . "\n";

    curl_multi_remove_handle($mh, $chs[$key]);

// close current handler

A possible return for this example could be:

The request to '' returned 'fruits' in 2 seconds.

The request to '' returned 'seafood' in 5 seconds.