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]
[previous exception] [object] (PDOException(code: 0): could not find driver
In this article, i will share with you h...How to check if an element is hidden using jQuery
Use the jQuery :hidden Selector The j...Laravel 5.5 - How To Make cURL HTTP Request Example
Today, we are share with you how to make...An error occurred during the signature verification. The following signatures were invalid
Sometimes, while updating repository key...How to create and customise login in laravel
Laravel has great features out of the bo...