curl_multi_await

The async equivalent to curl_multi_select

Description

function curl_multi_await(
  resource $mh,
  float $timeout = 1.0,
): Awaitable<int>

The async equivalent to curl_multi_select

This function waits until there is activity on a cURL handle within $mh. Once there is activity, you process the result with curl_multi_exec

Parameters

  • resource $mh - A cURL multi handle returned from curl_multi_init.
  • float $timeout = 1.0 - The time to wait for a response indicating some activity.

Return Values

  • \Awaitable<int> - - An Awaitable representing the int result of the activity. If returned int is positive, that represents the number of handles on which there was activity. If 0, that means no activity occurred. If negative, then there was a select failure.

Examples

The following shows a scenario where you are going to wait for and return the result of activity on multiple curl handles. A bit of a simpler approach would be to use HH\Asio\curl_exec, which is a wrapper around curl_multi_await.

<?hh

namespace Hack\UserDocumentation\API\Examples\cma;

async function get_curl_content(Set<string> $urls): Awaitable<Vector<string>> {

  $chs = Vector {};
  foreach ($urls as $url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $chs[] = $ch;
  }

  $mh = curl_multi_init();
  foreach ($chs as $ch) {
    curl_multi_add_handle($mh, $ch);
  }

  $active = -1;
  do {
    $ret = curl_multi_exec($mh, $active);
  } while ($ret == CURLM_CALL_MULTI_PERFORM);

  while ($active && $ret == CURLM_OK) {
    $select = await curl_multi_await($mh);
    if ($select === -1) {
      // https://bugs.php.net/bug.php?id=61141
      await \HH\Asio\usleep(100);
    }
    do {
      $ret = curl_multi_exec($mh, $active);
    } while ($ret == CURLM_CALL_MULTI_PERFORM);
  }

  $content = Vector {};

  foreach ($chs as $ch) {
    $str = (string) curl_multi_getcontent($ch);
    $content[] = substr($str, 0, 10);
    curl_multi_remove_handle($mh, $ch);
  }

  curl_multi_close($mh);

  return $content;
}

function run(): void {
  $urls = Set {'http://www.google.com', 'http://www.cnn.com'};
  $content = \HH\Asio\join(get_curl_content($urls));
  var_dump($content);
}

run();
Output
object(HH\Vector)#8 (2) {
  [0]=>
  string(10) "<!doctype "
  [1]=>
  string(10) "<!DOCTYPE "
}