"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Achieve Asynchronous cURL Requests in PHP?

How to Achieve Asynchronous cURL Requests in PHP?

Published on 2024-11-11
Browse:655

How to Achieve Asynchronous cURL Requests in PHP?

Asynchronous curl request in PHP

Executing multiple curl requests simultaneously can be a challenge in PHP. In this article, we'll explore different approaches to achieve asynchronous execution using built-in functions and external libraries.

cURL multi-threading

PHP's curl_multi_* functions allow for asynchronous execution of multiple cURL requests. Here's an example:

curl_multi_init();
$mh = curl_multi_init();

$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, 'http://example.com/endpoint');
curl_multi_add_handle($mh, $ch1);

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'http://example.com/endpoint2');
curl_multi_add_handle($mh, $ch2);

$active = null;
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, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

pthreads

The pthreads library allows for multi-threaded programming in PHP. Using pthreads, asynchronous curl requests can be achieved like this:

class RequestThread extends Thread {
    public function run() {
        $ch = curl_init();
        // ... set cURL options here

        curl_exec($ch);
        curl_close($ch);
    }
}

$thread = new RequestThread();
$thread->start();

Parallel execution using library

There are also libraries specifically designed for parallel execution in PHP, such as parallel-functions and parallel-request. Here's an example using the parallel-request library:

use Parallel\{Task, Runtime};

$runtime = new Runtime;

$tasks = [
    new Task(function () {
        // ... cURL request 1
    }),
    new Task(function () {
        // ... cURL request 2
    }),
];

$runtime->run($tasks);

Considerations

When executing asynchronous requests, it's important to consider the server's resource limits and potential bottlenecks. It's also crucial to handle errors and exceptions that may occur during execution.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3