In PHP, the curl_multi_init() function is used to initialize a session that can handle multiple cURL requests simultaneously. This function creates a new curl_multi handle and returns a resource handle. With this session handle, we can add multiple cURL request handles to the session, enabling parallel processing of multiple URLs.
resource curl_multi_init(void);
If successful, curl_multi_init() returns a session handle; if it fails, it returns FALSE.
Here is a simple example that shows how to use the curl_multi_init() function to initialize a session with multiple cURL requests and handle multiple requests simultaneously:
<?php
// Initialize session
$mh = curl_multi_init();
// Create URL list
$urls = array(
'http://www.example.com/url1',
'http://www.example.com/url2',
);
// Create cURL handles and add to the session
$handles = array();
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
// Execute cURL handles in the session
$active = null;
do {
$result = curl_multi_exec($mh, $active);
} while ($result == CURLM_CALL_MULTI_PERFORM || $active);
// Process results
foreach ($handles as $handle) {
$response = curl_multi_getcontent($handle);
// Handle response data
echo $response;
// Remove handle and close cURL
curl_multi_remove_handle($mh, $handle);
curl_close($handle);
}
// Close the session
curl_multi_close($mh);
?>
The code above first initializes a new cURL session with curl_multi_init(). Then, a list of URLs is defined, and each URL is processed in a loop where a cURL handle is created for each URL using curl_init(), and each handle is added to the session using curl_multi_add_handle().
Next, the curl_multi_exec() function is used to execute all the cURL requests within the session. Once the requests are completed, curl_multi_getcontent() is used to get the response data from each request, and further processing is done. Finally, the handles are removed from the session using curl_multi_remove_handle(), and each cURL handle is closed using curl_close(). The entire session is closed at the end using curl_multi_close().
By using the curl_multi_init() function, PHP programs can handle multiple cURL requests simultaneously, significantly improving performance, especially when making multiple API requests or downloading large amounts of data in parallel.
Mastering curl_multi_init() and its related functions will not only improve your PHP network request capabilities but also deepen your understanding of parallel requests and performance optimization.
Related Tags:
cURL