Parallel cURL

The curl extension starts every transfer from a handle, and a multi handle runs many of them in one wait. PHP drives the group with a small loop, which is why one HTTPS page can ask ten slow servers at the same time.

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.

<?php $multi = curl_multi_init(); $handles = []; $urls = ["https://example.com", "https://example.org"]; echo get_debug_type($multi), PHP_EOL; echo count($urls), PHP_EOL;

php multi.php

CurlMultiHandle
2

The group is a CurlMultiHandle of its own, and the URL list says how many easy handles will join it.

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.

<?php file_put_contents(__DIR__ . "/a.txt", "alpha"); file_put_contents(__DIR__ . "/b.txt", "beta"); $multi = curl_multi_init(); $handles = []; foreach (["a.txt", "b.txt"] as $name) { $ch = curl_init("file://" . __DIR__ . "/" . $name); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi, $ch); $handles[$name] = $ch; } echo count($handles), PHP_EOL; echo get_debug_type($handles["a.txt"]), PHP_EOL;

php queue.php

2
CurlHandle

The key of each entry is the name of the file it fetches, so a finished body can be printed next to its request. The files are written here for the same reason as in the previous lesson: the example prints the same answer on a machine with no network.

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.

<?php file_put_contents(__DIR__ . "/a.txt", "alpha"); file_put_contents(__DIR__ . "/b.txt", "beta"); $multi = curl_multi_init(); foreach (["a.txt", "b.txt"] as $name) { $ch = curl_init("file://" . __DIR__ . "/" . $name); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi, $ch); } $running = 0; do { curl_multi_exec($multi, $running); curl_multi_select($multi); } while ($running > 0); echo "running: ", $running, PHP_EOL;

php loop.php

running: 0

The counter is the second, by-reference argument of curl_multi_exec(): it starts unknown and ends at zero, which is the only proof that every transfer finished.

Collect responses

After the loop each handle holds its own answer. Read the content, detach the handle from the group, and leave the group itself to go out of scope: PHP 8.5 deprecates curl_close(), and since PHP 8.0 it frees nothing.

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

<?php file_put_contents(__DIR__ . "/a.txt", "alpha"); file_put_contents(__DIR__ . "/b.txt", "beta"); $multi = curl_multi_init(); $handles = []; foreach (["a.txt", "b.txt"] as $name) { $ch = curl_init("file://" . __DIR__ . "/" . $name); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi, $ch); $handles[$name] = $ch; } $running = 0; do { curl_multi_exec($multi, $running); curl_multi_select($multi); } while ($running > 0); foreach ($handles as $name => $ch) { echo $name, ": ", substr((string) curl_multi_getcontent($ch), 0, 100), PHP_EOL; curl_multi_remove_handle($multi, $ch); } curl_multi_close($multi);

php collect.php

a.txt: alpha
b.txt: beta

Every line names its request, because the body comes from the handle stored under that name. The removal inside the loop is what keeps the group empty before it is closed.

Exercises

  1. Add a third file and confirm that the collect loop prints three lines.
  2. Print curl_getinfo($ch, CURLINFO_EFFECTIVE_URL) beside each body.
  3. Remove one handle before the loop runs and explain what its body becomes.
  4. Count the loop passes with a variable and compare the count for one file and for three.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a multi handle add to one easy handle?

    Answer

    A group that runs several transfers during one wait

    The group holds many easy handles, and a single loop moves all of them forward together.

  2. What is the second argument of curl_multi_exec()?

    Answer

    The number of transfers still running, passed by reference

    The function writes the running count into that variable, and the loop repeats while it is above zero.

  3. Why does the collect loop call curl_multi_remove_handle()?

    Answer

    It detaches the finished handle from the group

    Removal is the step that frees the slot in the group; without it the group keeps the handle until it is destroyed.

  4. What does curl_multi_select() do inside the loop?

    Answer

    It waits for activity instead of spinning the CPU

    Select blocks until one of the sockets has news, so the loop sleeps instead of burning a core.

  5. What does this program print? <?php $multi = curl_multi_init(); $urls = ["https://example.com", "https://example.org", "https://example.net"]; echo get_debug_type($multi), " ", count($urls);

    Answer

    CurlMultiHandle 3

    The group has its own class, and the URL list is still the plain array of three strings.

  6. What does this program print? <?php file_put_contents(__DIR__ . "/a.txt", "alpha"); $multi = curl_multi_init(); $handles = []; foreach (["a.txt", "a.txt"] as $name) { $ch = curl_init("file://" . __DIR__ . "/" . $name); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi, $ch); $handles[] = $ch; } echo count($handles);

    Answer

    2

    The list holds two handles even though they point at one file; the group does not merge them.

  7. What does this program print? <?php file_put_contents(__DIR__ . "/a.txt", "alpha"); $multi = curl_multi_init(); $ch = curl_init("file://" . __DIR__ . "/a.txt"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi, $ch); $running = 0; do { curl_multi_exec($multi, $running); curl_multi_select($multi); } while ($running > 0); echo curl_multi_getcontent($ch);

    Answer

    alpha

    The loop finishes before the content is read, so the body is there in full.

  8. What does this program print? <?php file_put_contents(__DIR__ . "/a.txt", "alpha"); $multi = curl_multi_init(); $ch = curl_init("file://" . __DIR__ . "/a.txt"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi, $ch); $content = curl_multi_getcontent($ch); var_dump($content);

    Answer

    string(0) ""

    Nothing has run yet, so the handle holds no body and the read gives an empty string.

  9. Why does the collect example not call curl_close() on each handle?

    Answer

    Because PHP 8.5 deprecates the call and it has freed nothing since PHP 8.0

    The removal is the step that matters now; the close call is deprecated and does nothing.

  10. A loop runs curl_multi_exec() but never checks the running counter and reads each body at once. What goes wrong?

    Answer

    The bodies are still empty when they are read

    The transfers need loop passes to finish, and a read before the counter reaches zero sees nothing.

The programs on this page were run with PHP 8.5.13 (php -v) and its curl extension, with the commands shown above.

Article author: Arthur Isaev