PHP CURL Asynchronous

1

I have a PHP file that does a POST request via curl to another PHP file, I need to place this request inside a loop and do a 10 request at a time without worrying about the return, is there a way to do this request without have to wait for the answer to make the next call?

Ex: '

for ($i = 1; $i <= 10; $i++) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "/api/atualizar/$i");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSLVERSION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    // JSON de retorno 
    $jsonRetorno = trim(curl_exec($ch));
    $resposta = json_decode($jsonRetorno);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $err = curl_errno($ch);

    curl_close($ch);

    echo "Item $i enviado!";
}

?> '

    
asked by anonymous 30.11.2018 / 17:25

1 answer

1

You are able to do this query using the curl_multi_init and curl_multi_add_handle . Imagine you have a function that creates a request, returning the curl handler, as below:

function create_request($i) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "/api/atualizar/$i");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSLVERSION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    return $ch;
 }

Using the functions curl_multi_init and curl_multi_add_handle you can create a session and queue the requests, without waiting for the return. Something like:

$session = curl_multi_init();

for ($i = 0; $i < 10; $i++) {
    $ch = create_request($i);
    curl_multi_add_handle($ch, $session);
}

Then, with the curl_multi_exec function, you execute the queued calls.

do {
    $mrc = curl_multi_exec($session, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

You can remove this do / while if you do not want to wait for the answer (just call curl_multi_exec 1x).

    
30.11.2018 / 18:03