Home  >  Article  >  Backend Development  >  How Can I Execute Concurrent cURL Requests Asynchronously in PHP?

How Can I Execute Concurrent cURL Requests Asynchronously in PHP?

DDD
DDDOriginal
2024-11-02 05:43:02909browse

How Can I Execute Concurrent cURL Requests Asynchronously in PHP?

Asynchronous Execution of Concurrent cURL Requests in PHP

Introduction

Executing curl requests sequentially can result in performance issues, especially when dealing with multiple resource-intensive requests. This article explores asynchronous execution techniques to optimize curl request handling in PHP.

Asynchronous cURL

PHP provides built-in functions for asynchronous cURL execution using curl_multi_* commands. Here's a revised version of your code using this approach:

<code class="php">$mh = curl_multi_init();
curl_multi_add_handle($mh, $session); // session for the first request
curl_multi_add_handle($mh, $ch); // ch for the second request

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

while ($active & $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}
curl_multi_remove_handle($mh, $session);
curl_multi_remove_handle($mh, $ch);
curl_multi_close($mh);</code>

This approach uses curl_multi_exec() to execute both curl handles simultaneously.

pThreads

Another option is pThreads, a threading library for PHP. Here's an example of using this library:

<code class="php">class Request1 extends Thread {
    // ... your implementation
}

class Request2 extends Thread {
    // ... your implementation
}

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

This code creates two thread objects and starts them using the start() method. Each thread executes its own cURL request.

Resources

  • [PHP Manual - cURL Multipart Interface](https://www.php.net/manual/en/function.curl-multi-init.php)
  • [PHP Manual - Thread Class](https://www.php.net/manual/en/class.thread.php)

The above is the detailed content of How Can I Execute Concurrent cURL Requests Asynchronously 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