Mastering PHP’s curl_multi_close: Properly Release Multi‑Handle Resources
This guide explains how PHP’s curl_multi_close function releases resources allocated by curl_multi_init, demonstrates a complete example of creating, adding, and closing multiple cURL handles, and highlights best practices for efficient network request handling.
When performing network requests in PHP, developers often rely on the cURL extension. Among its many functions, curl_multi_close() is used to close a set of cURL sessions created with curl_multi_init(), freeing the resources they consume.
The curl_multi_close() call is essential for proper resource management. After all requests have been executed and responses processed, invoking this function ensures that the multi‑handle and any associated handles are released, preventing memory leaks and improving application performance.
Example Code
<?php
// Create a multi‑handle
$multiHandle = curl_multi_init();
// Add the first request
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, 'https://example.com/api/1');
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($multiHandle, $ch1);
// Add the second request
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'https://example.com/api/2');
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($multiHandle, $ch2);
// Execute and wait for all requests to finish
// ... (execution logic not shown)
// Close the multi‑handle and release resources
curl_multi_close($multiHandle);
?>In the example above, curl_multi_init() creates a multi‑handle that can manage several cURL sessions simultaneously. Two individual handles ( $ch1 and $ch2) are initialized with curl_init(), each configured with a distinct URL and the CURLOPT_RETURNTRANSFER option to capture the response.
Both handles are added to the multi‑handle using curl_multi_add_handle(). After the (omitted) execution loop that runs the requests and waits for their completion, curl_multi_close($multiHandle) is called to close the multi‑handle, automatically cleaning up the underlying resources for all added handles.
Conclusion
The curl_multi_close() function is a convenient and crucial tool for terminating the set of cURL sessions created by curl_multi_init(). Using it correctly guarantees timely resource release and helps maintain optimal performance when handling multiple network requests in PHP.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
