QA
Intermediate LevelPHP 8+

How do you execute multiple non-blocking HTTP requests in parallel using curl_multi_exec() in PHP?

❓ Interview Prompt: Explain non-blocking cURL multi handles, parallel HTTP fetching, event loops with curl_multi_select(), and performance gains.

Executing sequential cURL HTTP requests in a loop ('curl_exec()') blocks execution, making 5 API calls taking 1 second each require 5 full seconds total.

Parallel Execution with 'curl_multi_exec()':

'curl_multi_exec()' allows executing multiple HTTP requests concurrently on a single PHP thread using non-blocking I/O multiplexing. 5 parallel API calls complete in the time of the single slowest request (~1 second)!

Code Implementation Example

php
<?php
$urls = ['https://api.github.com/users/1', 'https://api.github.com/users/2'];
$mh = curl_multi_init();
$handles = [];

foreach ($urls as $url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'PHP App');
    curl_multi_add_handle($mh, $ch);
    $handles[] = $ch;
}

// Execute parallel requests concurrently
do {
    $status = curl_multi_exec($mh, $active);
    curl_multi_select($mh);
} while ($active && $status == CURLM_OK);

// Retrieve response payloads
foreach ($handles as $ch) {
    $content = curl_multi_getcontent($ch);
    curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
💡Executing parallel non-blocking HTTP requests using curl_multi_exec().
🎯 Interview Key Takeaway

Use curl_multi_exec() to execute parallel non-blocking HTTP requests concurrently on a single PHP thread.

#cURL#curl_multi_exec#Parallel HTTP#Intermediate
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?