Are there any best practices for limiting the number of requests per second when using multi_curl in PHP?
When using multi_curl in PHP to make multiple requests simultaneously, it's important to limit the number of requests per second to prevent overwhelming the server or hitting rate limits. One way to achieve this is by using a delay between each request using usleep() function. This will ensure that the requests are spaced out evenly over time.
$urls = ['http://example.com/api/1', 'http://example.com/api/2', 'http://example.com/api/3'];
$mh = curl_multi_init();
$handles = [];
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
foreach ($handles as $ch) {
curl_multi_exec($mh, $running);
usleep(100000); // Delay between each request in microseconds (100ms)
}
foreach ($handles as $ch) {
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
Related questions
-
Sorting algorithm PHP criteria
-
fopen fwrite fclose
-
What potential issues can arise when using language files in PHP Mailer 6 without specifying a path?PHP Mailer 6 language files path