How to get the return of multi Curl (curl_multi_add_handle)?

Asked

Viewed 553 times

1

I wanted to know how to get the return via multi Curl why by normal Curl just use the function curl_exec to get the result of the page but in the multi Curl I can’t get anything with the curl_exec.

1 answer

1


First, the curl_multi is not "compatible" with the functions of curl_*. That is, first you create Curl normally (using the curl_init() and the curl_setopt()), then add this Curl to Handle in curl_multi_add_handle.

Once you have the curl_multi_init, you should use only functions curl_multi_*.


To execute:

curl_multi_exec()

But, it has a "mystery", because the documentation itself will make the CPU go to 100%, or even enter an infinite loop.

There are two ways to contain this, using:

$executando = 1;
while($executando > 0){
    curl_multi_exec($mh, $executando);
    curl_multi_select($mh);
}

Another option would be to use the usleep:

$executando = 1;
while($running > 0){
    curl_multi_exec($mh, $executando);
    usleep(10);
}

Now how do I get the return, since everyone is inside the curl_multi_exec? There are other functions in comparison:

CURL                                   CURL MULTI 

curl_exec()                            curl_multi_exec()
                                       curl_multi_getcontent()

curl_close()                           curl_multi_remove_handle()
                                       curl_multi_close()

To obtain the curl_getinfo can directly use own curl_getinfo($ch), now if you want to get Curl Multi information, use curl_multi_info_read($mh) in his stead.


In an example of use, obtaining the content of multiple pages:

// Cria o primeiro cURL
$ch1 = curl_init('https://jsonplaceholder.typicode.com/posts/1');
curl_setopt_array($ch1, [
    CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_SSL_VERIFYPEER => 0,  // Isto é inseguro, não use isto em produção, altere para `1`.
    CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
    CURLOPT_FOLLOWLOCATION => 1,
    CURLOPT_RETURNTRANSFER => 1
]);

// Copia o primeiro cURL e muda a URL, criando um segundo cURL
$ch2 = curl_copy_handle($ch1);
curl_setopt($ch2, CURLOPT_URL, 'https://api.fixer.io/latest');

// Cria o cURL Multi
$mh = curl_multi_init();

// Importa os cURL criados
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

// Executa o cURL Multi
$running = 1;

while($running > 0){
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
}

// Exibe primeiro cURL:
echo curl_multi_getcontent($ch1);

// Exibe segundo cURL:
echo curl_multi_getcontent($ch2);

// Fecha o cURL Multi:
curl_multi_close($mh);

// Fecha o cURL:
curl_close($ch1);
curl_close($ch2);

This will return two distinct JSON, one is from this page and the other of this.

Browser other questions tagged

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