Rewriting an old PHP scraper around curl_multi

Scrape’s download loop now keeps a pool of parallel cURL transfers going and streams each file straight to disk.

Terminal output from Scrape downloading four PDFs from a test directory listing: all four Downloading lines appear together and are highlighted, then the progress reaches 4 of 4, ending in 4 successful, 0 failed and 0 skipped. Terminal output from Scrape downloading four PDFs from a test directory listing: all four Downloading lines appear together and are highlighted, then the progress reaches 4 of 4, ending in 4 successful, 0 failed and 0 skipped.

My oldest public repository is Scrape, which I wrote in 2010 while learning PHP, just before I joined Tigerfish. Point it at a web server with directory listings turned on, the “Index of /” pages a server shows for a folder with no home page, and it downloads the files.

In October 2025 I rewrote its download loop around cURL’s multi interface. It now runs ten transfers at once by default, up to 50, and streams every file straight to disk. In November 2026 I added retries and a suite of offline tests.

A pool of transfers

Before the rewrite the class did one file at a time. It sent a get_headers() request for each file, following any Location header, just to learn its length, then downloaded with a Range header into a temporary file in the cache folder and appended that to the real file, looping until the file on disk was as long as the server said. Every download waited for the one before it, and paid for an extra request.

Now it keeps a queue of files, a pool of active transfers and a list of retries waiting their turn. This is the shape of downloadInParallel() in scraper.class.php:

while (!empty($queue) || !empty($waiting) || !empty($active)) {
    // Fill the active pool, retries that are due first
    while (count($active) < $this->maxConcurrentDownloads) {
        // ...take a due retry, or the next file in the queue...
        // ...skip long paths, create the folder, skip files already on disk...
        $ch = $this->createCurlHandle($link['link'], $fp);
        curl_multi_add_handle($mh, $ch);
    }

    do {
        $status = curl_multi_exec($mh, $running);
    } while ($status === CURLM_CALL_MULTI_PERFORM);

    // Wait for activity, but not past the next retry time
    if ($running > 0) {
        curl_multi_select($mh, $timeout);
    }
    // ...collect finished transfers with curl_multi_info_read()...
}

Each pass tops the pool up, lets cURL move every transfer along, and waits up to half a second for something to happen, or less if a retry is due sooner. Finished transfers are read off and their places freed for the next pass.

Retries that don’t hold up the rest

A transfer that fails with a network error, a timeout (HTTP 408), a rate limit (429) or a server error (5xx) goes on the waiting list instead of failing the run. It’s tried again after a delay of two seconds by default, doubling with each attempt, up to three retries by default, and the other transfers keep running meanwhile. A 404 or any other client error is final: asking again won’t change the answer.

Streaming to disk

Each handle writes straight to a file: the loop opens <name>.part and passes it to cURL with CURLOPT_FILE, so memory use doesn’t grow with the size of the download. Only a transfer that finishes with a 2xx status is renamed into place, so an error page is never saved as a file and a half-finished download never looks like a whole one. The handles also share a cache:

// Connection pooling for better performance
if ($this->curlShareHandle === null) {
    $this->curlShareHandle = curl_share_init();
    curl_share_setopt($this->curlShareHandle, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
    curl_share_setopt($this->curlShareHandle, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
    curl_share_setopt($this->curlShareHandle, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);
}
curl_setopt($ch, CURLOPT_SHARE, $this->curlShareHandle);

DNS answers, TLS sessions and open connections are shared between handles, so many files from one server don’t each pay for a lookup and a handshake. A transfer slower than 10KB a second for a minute is abandoned. Connection and transfer timeouts (30 and 300 seconds by default) and an optional bandwidth limit are there too.

Walking the listings

Listing pages are fetched one at a time as the class walks the tree, with a regular expression pulling out the links. Only links below the starting address are followed, so a listing can’t lead it off to another site. A link ending in a slash is a folder to walk into; anything else is a file, and it goes on the list if it passes the type, path, name and search filters and isn’t already on disk.

Offline tests

php tests/run.php starts PHP’s built-in web server on a free local port with a fake “Index of /” listing, and runs 28 checks against it in about three seconds, with no network. They cover the content of every file downloaded, a 404 that is neither saved nor retried, a file that fails twice and is fetched on the third try with the right gaps, files already on disk left alone, the type filter, exclusions and search mode.

Search first

The class is a single file to read or copy. A search run lists what would be downloaded without creating anything:

require_once 'scraper.class.php';

$scraper = new scraper();
$scraper->setDestinationRoot('./downloads/')
    ->setMode('search')
    ->addLocation('https://example.com/files/', 'example', ['pdf'])
    ->scrape();

When the list looks right, take out setMode('search') and run it from the command line:

php scrape.php

scrape() turns off PHP’s time limit and prints its progress as it goes.

Featured projects

All projects

Latest writing

All writing