When using PHP's curl_multi_* series functions, curl_multi_close is used to close a handle created by curl_multi_init . But many developers will be confused before calling curl_multi_close :
The answer is: It is usually not needed, but it is still a good habit to manage resources reasonably.
According to the official PHP documentation, the function of curl_multi_close is to destroy a cURL multi handle and automatically release the resources associated with the multi handle. However, it does not automatically close the individual cURL handles created by curl_init and added to the multi handle. You need to manually close each individual cURL handle using curl_close before calling curl_multi_close .
If you do not, these separate cURL handles still occupy memory resources, which may lead to memory leaks.
Here is a PHP example that correctly manages multi handles and single curl handles:
<?php
// Initialize multiple curl Handle
$ch1 = curl_init('https://gitbox.net/api/endpoint1');
$ch2 = curl_init('https://gitbox.net/api/endpoint2');
// Create a curl_multi Handle
$mh = curl_multi_init();
// 添加Handle到 multi handle
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);
// implement
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
// 移除Handle
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
// 关闭单个Handle
curl_close($ch1);
curl_close($ch2);
// Last Close multi handle
curl_multi_close($mh);
?>
In the above code:
First use curl_multi_remove_handle to remove a single handle from the multi handle;
Then curl_close individually closes each curl handle;
Finally, use curl_multi_close to close the multi handle itself.
This ensures that all resources are released correctly without legacy handles or memory leaks.
curl_multi_close is only responsible for the destruction of the multi handle itself;
A single curl handle requires you to manually close;
There is no need to check the "status" of the handle, but it is necessary to make sure that each individual curl handle is removed and closed ;
Developing good resource management habits is the key to avoiding memory leaks and waste of system resources.