Asynchronous Requests with PHP

PHPPosted on

We know that we can send requests to form PHP – for example with the help of cURL –, but can we send multiple requests in multiple threads to make the whole process faster?

Building a Multi-Thread cURL Request

Generally, we could handle multiple requests after each other. That means, first we trigger the first one and process the response, then the second and third and so on. Now, this process is slow and time-consuming. But cURL offers the curl_multi_* functions to handle asnyc requests. Let’s see the code.

$running = null;
$mh = curl_multi_init();

$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, '');
// Other curl options....
curl_multi_add_handle($mh, $ch1);

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, '');
// Other curl options.... 
curl_multi_add_handle($mh, $ch2);

do {
    curl_multi_exec($mh, $running);
} while ($running > 0);

$r1 = curl_multi_getcontent($ch1);
$r2 = curl_multi_getcontent($ch2);
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);

We can find the responses in the $r1 and the $r2 variable.

With the help of these cURL functions, we can trigger requests parallelly, so we save time and we can process the responses quicker.

In my opinion, it’s not that elegant like a closure based JS asnyc request, but still it’s awesome we have this option in PHP as well!

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in PHP category