PHP CURL Asynchronous

Asked

Viewed 768 times

2

I have a PHP file that makes a POST request via Curl to another PHP file, I need to put this request inside a loop and make a 10 request at once without worrying about the return, there is a way to make this request without having 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!";
}

?>`

1 answer

1


You are able to make this query using the functions curl_multi_init and curl_multi_add_handle. Imagine you have a function that creates a request, returning 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 function of curl_multi_exec you run the queued calls.

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

You can remove this from/while if you don’t want to wait for the answer (you just have to call curl_multi_exec 1x).

  • Perfect exactly as I expected. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.