SoFunction
Updated on 2025-03-10

Four ways to implement asynchronous requests in PHP

The cURL in PHP can be used to initiate HTTP requests, usually waiting for the server to respond synchronously. If you want to implement asynchronous operations, i.e., the PHP program continues to execute without waiting for the cURL request to complete, you can consider the following ways:

Use curl_multi

cURL provides settingscurl_multiandcurl_multi_execTo handle multiple requests at the same time, you need to write a callback function to process the results of each request.

$urls = [
    '/api/endpoint1',
    '/api/endpoint2',
    // ...More URLs];
 
$multiHandle = curl_multi_init();
 
foreach ($urls as $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($multiHandle, $ch);
}
 
$running = null;
do {
    usleep(10000); // Optional: Prevent the CPU from running at full speed    curl_multi_exec($multiHandle, $running);
} while ($running > 0);
 
foreach ($urls as $url) {
    $ch = curl_multi_getcontent($ch);
    // Processing results    curl_multi_remove_handle($multiHandle, $ch);
}
 
curl_multi_close($multiHandle);

Using pthreads

Although PHP itself is not a native language that supports multithreading, it can create and manage threads with the help of the pthreads extension to let cURL run in another thread.

<?php
require 'vendor/';
$promise = new \React\Promise\Promise(function ($resolve, $reject) {
    // Create cURL operation    $ch = curl_init();
    // Set request options...    curl_setopt($ch, CURLOPT_URL, '');
    // Create a new React asynchronous client    $client = new \React\Curl\Adapter\Curl();
    // Make a request using React asynchronous library    $response = $client->enqueue($ch);
    // When the request is completed, call resolve or reject function    $response->then(
        function ($result) use ($resolve) { $resolve(json_decode($result)); },
        function ($error) use ($reject) { $reject($error); }
    );
});
// At the same time, the main thread continues to execute other tasks$promise->wait(); // When cURL is finished, blocking here?>

Using the Guzzle library

Guzzle is a powerful HTTP client library that can be used to send asynchronous HTTP requests. It provides convenient interfaces and functions to make sending asynchronous requests easier. Here is a sample code for sending asynchronous requests using the Guzzle library:

$client = new \GuzzleHttp\Client();
$promises = [
    'api1' => $client->getAsync('/api1'),
    'api2' => $client->getAsync('/api2'),
];
$results = \GuzzleHttp\Promise\Utils::settle($promises)->wait();
$response1 = $results['api1']['value']->getBody()->getContents();
$response2 = $results['api2']['value']->getBody()->getContents();
// Process response data// …

The above code initializes an HTTP client instance through the GuzzleHttp\Client class, then sends an asynchronous GET request using the getAsync method, and stores the returned Promise object in the $promises array. Next, wait for all Promise objects through the \GuzzleHttp\Promise\Utils::settle method and obtain the response data through the getBody method. Finally, the obtained response data can be processed.

Extensions with Swoole

Swoole is a high-performance asynchronous parallel network communication framework that can be used to implement asynchronous programming of PHP. Asynchronous requests can be easily implemented by using Swoole extensions. Here is a sample code for sending asynchronous requests using Swoole extension:

$cli1 = new Swoole\Coroutine\Http\Client('', 80);
$cli1->set(['timeout' => 10]);
$cli1->get('/api1');
$cli2 = new Swoole\Coroutine\Http\Client('', 80);
$cli2->set(['timeout' => 10]);
$cli2->get('/api2');
Swoole\Event::wait();
$response1 = $cli1->body;
$response2 = $cli2->body;
// Process response data// …

The above code initializes two HTTP client instances using the Swoole\Coroutine\Http\Client class, and then sends an asynchronous GET request through the get method. Next, wait for all requests to be completed through the Swoole\Event::wait method and obtain the response data through the body attribute. Finally, the obtained response data can be processed.

Summarize

The above are several commonly used methods to implement asynchronous requests in PHP. You can choose appropriate methods to implement asynchronousization according to specific needs. In general, there are many methods to choose from for asynchronous requests in PHP, each method has its own characteristics and applicable scenarios. Choosing the right method depends on the specific requirements and project conditions.

This is the end of this article about four methods for PHP to implement asynchronous requests. For more related content on PHP to implement asynchronous requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!