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.

php Courses
php Courses
php Courses
Using curl_multi_close() to Properly Close Multiple cURL Sessions in PHP

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<br/>// 创建多个cURL会话<br/>$multiHandle = curl_multi_init();<br/><br/>// 添加第一个请求<br/>$ch1 = curl_init();<br/>curl_setopt($ch1, CURLOPT_URL, 'https://example.com/api/1');<br/>curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);<br/>curl_multi_add_handle($multiHandle, $ch1);<br/><br/>// 添加第二个请求<br/>$ch2 = curl_init();<br/>curl_setopt($ch2, CURLOPT_URL, 'https://example.com/api/2');<br/>curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);<br/>curl_multi_add_handle($multiHandle, $ch2);<br/><br/>// 执行并等待所有请求完成<br/>// ...<br/><br/>// 关闭会话<br/>curl_multi_close($multiHandle);<br/>?>

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPcURLNetwork Requestscurl_multi_close
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.