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.
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
-
Apple News API
Publish articles and live coverage to Apple News from PHP, with the whole Apple News Format built from objects.
-
GitHub Auditor
Health, access and activity reports for more GitHub and Bitbucket repositories than you can keep in your head.
-
PrintMD
Markdown in, and a designed PDF, Word or PowerPoint file out. Its PDF service runs on your own computer.
-
Where Should I Live
Which city would leave you best off? Cities ranked by take-home pay, living costs, visas and the way you live.
-
Solar Calendar
Thirteen months of exactly four weeks, with the year starting on the first Monday on or after the spring equinox.
Latest writing
-
Many sessions at once, and what still needs me
Fifteen coding-agent sessions across two Linux boxes, one session that watches the rest, what it may answer for me, what it never may, and why a yes it passes on gets checked against what I typed.
-
61 public repos of agent tooling, none installed, six ideas kept
One author, 61 public repositories of coding-agent tooling: what I checked before any of it got near my Linux boxes, why none of it was installed, and the six ideas I built my own way.
-
Rules a coding agent cannot talk its way round
The hook that reads every command a coding agent wants to run on my Linux boxes: what it refuses, the 27 proofs that its tests fail when a rule is taken out, and the four lines every report opens with.
-
Dozens of repos, one person
46 repositories and two Linux boxes with nobody else on them: the diary, the decision table, the rebuild guide and the job that keeps both sets of clones in step.