Processing a 2 GB CSV in PHP Without Running Out of Memory
file() and fetchAll() load everything into RAM and die on big datasets. Generators stream one row at a time with constant memory - and the code barely changes.
Software Engineer
I build web applications and share what I learn along the way.
Step-by-step programming tutorials on PHP, JavaScript, Laravel, WordPress and more.
file() and fetchAll() load everything into RAM and die on big datasets. Generators stream one row at a time with constant memory - and the code barely changes.
strtotime and DateTime parse a small English grammar - "last day of next month", "second friday of january" - that replaces whole functions of calendar math.
Users almost never report the JavaScript errors they hit. A global error handler, sendBeacon and a tiny PHP endpoint give you a self-hosted crash log for free.
fetch() still cannot report upload progress reliably - but XMLHttpRequest has done it for fifteen years. The full pattern: progress events, a PHP receiver, and the config limits that silently break big uploads.
Sending the confirmation email should not make the customer stare at a spinner. PHP can close the HTTP response and keep working - if you know which runtime you are on.
FETCH_KEY_PAIR, FETCH_UNIQUE, FETCH_GROUP and FETCH_COLUMN reshape query results at fetch time - the id-indexed maps and grouped arrays you keep building with foreach loops.
match() is not just a stricter switch. Feed it true as the subject and every arm becomes an arbitrary condition - an elegant, exhaustive replacement for elseif ladders.
A PHP script renamed to photo.jpg sails past extension checks. finfo reads the actual bytes. Here is the upload validation layer cake that actually holds.
WebSockets need infrastructure. Polling hammers your server. SSE streams live updates over normal HTTP with a PHP file and the built-in EventSource API - reconnection included.
The third parameter turns array_column into a re-indexing tool, it reads object properties, and combined with array_map it handles most of your collection reshaping.
Comparing secrets with === leaks how many leading characters matched, one microsecond at a time. hash_equals exists for exactly this, and knowing when to use it is the whole trick.
?->, ??=, throw as an expression, and the spaceship - four small operators from recent PHP that collectively delete the noisiest guard code in legacy files.