Using PHP curl_multi_add_handle() to Manage Multiple cURL Handles
This article explains how the PHP curl library’s curl_multi_add_handle() function can combine multiple cURL handles into a single multi‑handle session, provides its syntax and parameters, and demonstrates its usage with a complete example that improves network request efficiency.
The PHP curl library is a widely used tool for performing HTTP requests such as GET and POST, setting headers, and handling cookies.
When many requests need to be sent simultaneously, creating a separate cURL handle for each can waste resources; the curl_multi_add_handle() function allows multiple handles to be added to one multi‑handle session for efficient management.
The syntax of curl_multi_add_handle() is:
resource curl_multi_add_handle ( resource $mh , resource $ch )$mh is an initialized cURL multi‑handle, and $ch is the individual cURL handle to be added; the function returns a cURL multi‑handle.
Below is a practical example that initializes a multi‑handle, creates two independent cURL handles for different URLs, adds them to the multi‑handle, executes the requests in a loop until all are complete, retrieves each response, and finally removes the handles and closes the session.
<?php
$mh = curl_multi_init(); // initialize multi‑handle
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, "https://www.example.com/api1");
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch1); // add first handle
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, "https://www.example.com/api2");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch2); // add second handle
// execute until all requests are done
do {
$status = curl_multi_exec($mh, $running);
} while ($status === CURLM_CALL_MULTI_PERFORM || $running);
// get results
$response1 = curl_multi_getcontent($ch1);
echo "Response 1: " . $response1 . "\n";
$response2 = curl_multi_getcontent($ch2);
echo "Response 2: " . $response2 . "\n";
// clean up
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
?>The example demonstrates initializing the multi‑handle with curl_multi_init() , creating two separate handles ( $ch1 and $ch2 ), adding them to the session, looping with curl_multi_exec() until completion, retrieving each response via curl_multi_getcontent() , and finally cleaning up with curl_multi_remove_handle() and curl_multi_close() .
Using curl_multi_add_handle() together with related functions such as curl_multi_remove_handle() and curl_multi_close() enables efficient management of multiple concurrent network requests, improving performance and code maintainability in PHP backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.