Home >Backend Development >PHP Tutorial >How Can I Execute Multiple cURL Requests Simultaneously in PHP?

How Can I Execute Multiple cURL Requests Simultaneously in PHP?

DDD
DDDOriginal
2024-10-30 14:09:11727browse

How Can I Execute Multiple cURL Requests Simultaneously in PHP?

Async Curl Requests in PHP

In PHP, executing multiple cURL requests simultaneously can be challenging. This can result in inconsistent behavior, with some requests failing to execute. To address this issue, there are two main approaches: using asynchronous/parallel processing libraries or utilizing the built-in asynchronous cURL functions.

1. Asynchronous cURL

To use the built-in functions, you can implement the following:

<code class="php">$mh = curl_multi_init();
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active &amp;&amp; $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}
//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);</code>

2. pThreads

pThreads is a popular threading library for PHP. To use it:

<code class="php">class Request1 extends Thread {
    public function run() {
        // Execute the first curl request
    }
}


class Request2 extends Thread {
    public function run() {
        // Execute the second curl request
    }
}

$req1 = new Request1();
$req1->start();
$req2 = new Request2();
$req2->start();</code>

These approaches allow you to execute multiple cURL requests simultaneously, ensuring that they are all executed in a timely manner.

The above is the detailed content of How Can I Execute Multiple cURL Requests Simultaneously in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn