Using curl_multi_close() to Properly Close Multiple cURL Sessions in PHP
This article explains the purpose and proper usage of PHP's curl_multi_close() function, showing how it releases resources allocated by curl_multi_init() through a detailed example that creates, executes, and then cleanly closes multiple cURL sessions.
When making network requests in PHP, the cURL library is commonly used, and the curl_multi_close() function is essential for closing multiple cURL sessions.
The curl_multi_close() function releases resources allocated by curl_multi_init() , and calling it after all requests have been processed is good practice.
Example code demonstrates creating a multi‑handle with curl_multi_init() , adding two individual requests via curl_init() and curl_multi_add_handle() , and finally closing the multi‑handle with curl_multi_close() .
<?php
// 创建多个cURL会话
$multiHandle = curl_multi_init();
// 添加第一个请求
$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);
// 添加第二个请求
$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);
// 执行并等待所有请求完成
// ...
// 关闭会话
curl_multi_close($multiHandle);
?>The example explains each step: initializing the multi‑handle, setting up separate cURL handles, adding them to the multi‑handle, executing the requests, and closing the handle to free resources.
In summary, curl_multi_close() reliably terminates the sessions created by curl_multi_init() , ensuring timely resource release and improved performance for network‑intensive PHP applications.
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.