How PHP Handles Parallel Asynchronous HTTP Requests

Business cooperation WeChat: 2230304070

Learning and communication:PHP Technical Communication WeChat Group

2025 JetBrains universal activation code & account supports the latest version

https://www.mano100.cn/thread-1942-1-1.html

In PHP, due to its traditional synchronous blocking model, implementing parallel asynchronous handling of HTTP requests is not as straightforward as in other languages (such as Go or Node.js).

However, it is still possible to achieve parallel asynchronous processing through some extensions and tools. Here are several common methods:

1. Using cURL Multi-threading Features

The cURL extension in PHP supports multi-threaded processing, allowing for parallel HTTP requests through the curl_multi_* series of functions.

Example Code:

$urls = [
    'https://example.com/api/1',
    'https://example.com/api/2',
    'https://example.com/api/3',
];

$mh = curl_multi_init(); // Initialize multi-threaded cURL
$handles = [];

foreach ($urls as $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($mh, $ch); // Add individual cURL handle to multi-threaded
    $handles[] = $ch;
}

$running = null;
do {
    curl_multi_exec($mh, $running); // Execute parallel requests
    curl_multi_select($mh); // Wait for activity
} while ($running > 0);

$responses = [];
foreach ($handles as $ch) {
    $responses[] = curl_multi_getcontent($ch); // Get response for each request
    curl_multi_remove_handle($mh, $ch); // Remove handle
    curl_close($ch);
}

curl_multi_close($mh); // Close multi-threaded cURL

print_r($responses);

Advantages:

  • Native support, no additional extensions required.

  • Can handle multiple HTTP requests in parallel.

Disadvantages:

  • Higher code complexity.

  • Requires manual management of handles and states.

》》Laravel idea genuine activation code《《

How PHP Handles Parallel Asynchronous HTTP Requests

2. Using Guzzle Asynchronous Client

Guzzle is a popular PHP HTTP client library that supports asynchronous requests.

Example Code:

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Promise;

$client = new Client();

$urls = [
    'https://example.com/api/1',
    'https://example.com/api/2',
    'https://example.com/api/3',
];

$promises = [];
foreach ($urls as $url) {
    $promises[] = $client->getAsync($url); // Initiate asynchronous requests
}

$responses = Promise\Utils::settle($promises)->wait(); // Wait for all requests to complete

foreach ($responses as $response) {
    if ($response['state'] === 'fulfilled') {
        echo $response['value']->getBody() . "\n"; // Output response content
    } else {
        echo 'Request failed: ' . $response['reason']->getMessage() . "\n";
    }
}

Advantages:

  • Concise code, easy to use.

  • Supports concurrent requests and asynchronous processing.

Disadvantages:

  • Requires installation of the Guzzle library.

3. Using Swoole Extension

Swoole is a high-performance PHP extension that supports asynchronous, coroutine, and parallel processing.

Example Code:

Swoole\Runtime::enableCoroutine(); // Enable coroutines

$urls = [
    'https://example.com/api/1',
    'https://example.com/api/2',
    'https://example.com/api/3',
];

$responses = [];

go(function () use ($urls, &$responses) {
    $client = new Swoole\Coroutine\Http\Client('example.com', 443, true);
    foreach ($urls as $url) {
        $client->get($url);
        $responses[] = $client->body;
    }
});

Swoole\Event::wait(); // Wait for all coroutines to complete

print_r($responses);

Advantages:

  • High performance, supports coroutines and asynchronous I/O.

  • Suitable for high concurrency scenarios.

Disadvantages:

  • Requires installation of the Swoole extension.

  • Higher learning curve.

4. Using ReactPHP

ReactPHP is an event-driven PHP library that supports asynchronous programming.

Example Code:

require 'vendor/autoload.php';

use React\EventLoop\Factory;
use React\HttpClient\Client;
use React\HttpClient\Response;

$loop = Factory::create();
$client = new Client($loop);

$urls = [
    'https://example.com/api/1',
    'https://example.com/api/2',
    'https://example.com/api/3',
];

foreach ($urls as $url) {
    $request = $client->request('GET', $url);
    $request->on('response', function (Response $response) {
        $response->on('data', function ($chunk) {
            echo $chunk;
        });
    });
    $request->end();
}

$loop->run();

Advantages:

  • Event-driven, suitable for asynchronous programming.

  • Supports long connections and streaming processing.

Disadvantages:

  • Requires installation of the ReactPHP library.

  • Higher code complexity.

5. Using Multi-Processing (pcntl Extension)

The pcntl extension in PHP supports multi-processing programming, allowing for parallel processing by creating child processes.

Example Code:

$urls = [
    'https://example.com/api/1',
    'https://example.com/api/2',
    'https://example.com/api/3',
];

$children = [];

foreach ($urls as $url) {
    $pid = pcntl_fork();
    if ($pid == -1) {
        die('Could not fork');
    } elseif ($pid) {
        $children[] = $pid; // Parent process records child process ID
    } else {
        // Child process handles request
        echo file_get_contents($url) . "\n";
        exit(); // Child process exits
    }
}

// Parent process waits for all child processes to complete
foreach ($children as $pid) {
    pcntl_waitpid($pid, $status);
}

Advantages:

  • True parallel processing.

  • Suitable for CPU-intensive tasks.

Disadvantages:

  • Requires pcntl extension.

  • Inter-process communication is complex.

Conclusion

  • cURL Multi-threading: Suitable for simple parallel HTTP requests.

  • Guzzle: Concise code, suitable for most scenarios.

  • Swoole: High performance, suitable for high concurrency scenarios.

  • ReactPHP: Event-driven, suitable for asynchronous programming.

  • Multi-processing: Suitable for CPU-intensive tasks, but with higher complexity.

Choose the appropriate method based on specific needs.

How PHP Handles Parallel Asynchronous HTTP RequestsReference Links:This concludes the content of this article,I hope all programmers strive to improve their personal skills.Finally, a gentle reminder from the editor: read for 5 minutes every day, learn a little every day, and improve a little every day.

Leave a Comment