After creating a cURL handle with curl_init() , the resource will occupy system memory. After the request is completed, calling curl_close() can free the resource.
$ch = curl_init('https://gitbox.net/api/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch); // Free up resources
Note: After calling curl_close , the cURL resource handle cannot be used again, otherwise an error will be reported.
When you need to process multiple requests at the same time, you can create multiple cURL handles:
$urls = [
'https://gitbox.net/api/user',
'https://gitbox.net/api/product',
'https://gitbox.net/api/order',
];
$curlHandles = [];
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlHandles[] = $ch;
}
Here we store all handles in the array $curlHandles for easy unified management.
After completing the request, it needs to be released one by one:
foreach ($curlHandles as $ch) {
$response = curl_exec($ch);
// deal with $response ...
curl_close($ch); // Release each handle
}
This ensures that each handle is closed correctly and avoids resource leakage.
PHP provides curl_multi extension, which can handle multiple cURL handles at the same time, making it more efficient.
$mh = curl_multi_init();
$curlHandles = [];
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$curlHandles[] = $ch;
}
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
foreach ($curlHandles as $ch) {
$response = curl_multi_getcontent($ch);
// deal with $response ...
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
Here, curl_multi_close releases the multi-handle manager resource, while curl_close releases a single handle resource.
Be sure to call curl_close to free a single cURL handle.
When using curl_multi , first use curl_multi_remove_handle to remove the handle, and then call curl_close .
Avoid using the handle again after calling curl_close .
When managing multiple handles, use arrays to store them in a unified manner to facilitate batch release.
After freeing up resources, try to destroy variable references (for example, using unset ) so that PHP garbage collection is more efficient.
Correctly managing multiple cURL resources can significantly improve program stability and memory usage efficiency.