Parallel cURL

Multi handle

A multi handle runs several requests during the same wait time. Create it first, then attach one easy handle per URL.

This approach beats serial loops when fetching feeds, images, and status checks from many hosts.

$multi = curl_multi_init(); $handles = []; $urls = ["https://example.com", "https://example.org"];

Add handles

Each queued handle keeps its own options while sharing the run loop. Set return transfer, then add the handle to the group.

Store every handle in an array so results can be matched back to their requests later.

foreach ($urls as $url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi, $ch); $handles[] = $ch; }

Run the loop

The loop drives all transfers forward until none remain active. Select pauses briefly so the CPU stays idle while waiting.

Repeat exec and select while the running counter stays above zero.

$running = 0; do { curl_multi_exec($multi, $running); curl_multi_select($multi); } while ($running > 0);

Collect responses

After the loop each handle holds its own answer. Read the content, detach the handle, and close both levels when done.

Always remove easy handles before closing the multi handle to avoid leaking connections.

foreach ($handles as $ch) { echo substr((string) curl_multi_getcontent($ch), 0, 100); curl_multi_remove_handle($multi, $ch); curl_close($ch); } curl_multi_close($multi);

Next: XML with SimpleXML and DOM

Автор статьи: Arthur Isaev

Изображение баннера