In this article, i will share with you how to send simultaneous cURL requests in PHP using the curl_multi_exec() function with example. you all use cURL in PHP many times to call any third-party API in your application. but many developers still not know how to make simultaneous cURL requests make in PHP using the curl_multi_exec() function. when we need more than one request call at the same time then curl_multi_exec() is better for the reduce our execution time in an application.
By using curl_multi_exec, We can execute all these requests in parallel, and we will only be limited by the slowest request.
// array of curl handles
$multiCurl = array();
// data to be returned
$result = array();
// multi handle
$mh = curl_multi_init();
foreach ($ids as $i => $id) {
// URL from which data will be fetched
$fetchURL = 'https://laravelcode.com&postID='.$id;
$multiCurl[$i] = curl_init();
curl_setopt($multiCurl[$i], CURLOPT_URL,$fetchURL);
curl_setopt($multiCurl[$i], CURLOPT_HEADER,0);
curl_setopt($multiCurl[$i], CURLOPT_RETURNTRANSFER,1);
curl_multi_add_handle($mh, $multiCurl[$i]);
}
$index=null;
do {
curl_multi_exec($mh,$index);
} while($index > 0);
// get content and remove handles
foreach($multiCurl as $k => $ch) {
$result[$k] = curl_multi_getcontent($ch);
curl_multi_remove_handle($mh, $ch);
}
// close
curl_multi_close($mh);
$result[0] => {"id1":{"tag":"laravel","category":...
$result[1] => {"id2":{"tag":"python","category":...
....
i hope you like this solution.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to add elements to the end of an array in PHP
Use the PHP array_push() funct...How to count all elements or values in an array in PHP
Use the PHP count() or si...Laravel 8 - Custom server side search with datatable example
In this article, i will share with you h...How to sort an associative array by key in PHP
Use the PHP ksort() and k...How to create custom select box in HTML using CSS and jQuery
Use the CSS :selected Pseudo-class with...