App-owned bounded CSV exports in Laravel PHP
Scope and provenance
Replace one FastExcel CSV export with an app-owned job/controller and PHP's fputcsv. Keep spreadsheet libraries for XLSX/ODS, styles, multi-sheet workbooks or imports. This recipe is a bounded CSV path, not a full package replacement for applications using those features. Compare the package/framework refs in this recipe's metadata with the destination composer.lock and PHP runtime before editing.
FastExcel by Raphaël Huchet is MIT licensed. Inspect src/FastExcel.php, src/Exportable.php and tests/FastExcelTest.php. Retain its notices for adapted source/fixtures. FastExcel delegates file encoding to OpenSpout; the direct CSV path does not copy that engine. No destination application has been converted or trialed with this guidance.
Source behavior and explicit differences
If the installed FastExcel follows the inspected implementation, it selects the writer from the filename, infers headers from the first projected row and accepts collections/arrays/traversables. Mapping callbacks may skip null/false rows. CSV settings include delimiter/enclosure/BOM. Traversable output can stream, but a preloaded collection is already in memory and transpose buffers data.
Use a fixed export schema ID,Name,JoinedAt, UTF-8 comma-separated fields, CRLF record endings, no BOM, and headers even when there are no rows. Always project all fields in this order; null name becomes an empty string, IDs remain decimal strings and timestamps are explicitly formatted in UTC. These are deliberate differences from first-row/header inference. CSV cannot force Excel to preserve leading zeros or long numeric IDs; use a typed workbook if that is a requirement.
Implement the export operation
- Authorize the operation before any query. Establish tenant/user scope and select only allowed columns. Do not export
$model->toArray()wholesale or let request fields choose raw column identifiers, storage paths or headers. Bound rows, bytes per cell, output bytes and job duration. - Stage output in a uniquely owned private file opened exclusively beneath a trusted root, never in public storage. On query/projection/write/close failure, remove the partial file and do not mark the export ready. Publish a completed artifact only after successful finalization. Keep it until the final response reader finishes; cleanup in an outer function that only returns a streaming callback runs too early.
- Use
lazyById()/chunkById()on a scoped query with a stable unique key, or another proven bounded iterator. Avoidget()and unbounded collections. Cursor implementations can still buffer in the database driver, so measure memory on the actual driver. Define snapshot versus live-scan consistency; a captured maximum ID excludes newer high IDs but does not freeze updates or deletions. - Write a fixed header followed by positional arrays with explicit error handling. If the destination PHP exposes the six-argument
fputcsvAPI, use an empty escape argument rather than the historical backslash default:
if (fputcsv($handle, ['ID', 'Name', 'JoinedAt'], ',', '"', '', "\r\n") === false) {
throw new \RuntimeException('Could not write CSV header.');
}
// For every authorized row: validate policy, project all three cells,
// then fputcsv($handle, [$id, $name, $joinedAt], ',', '"', '', "\r\n").
// Treat false as failure on every row, not just the header.
if (!fflush($handle)) {
throw new \RuntimeException('Could not flush CSV.');
}
// Check fclose($handle) before marking the staged artifact ready.
The surrounding operation owns $handle, exception reporting and cleanup in finally. Verify the runtime API before adopting this fragment; do not use unsupported arguments or silently choose a different escaping dialect. Do not build CSV using implode(',').
- Apply a separate spreadsheet-input policy. CSV quotation does not disable formulas. For this bounded human-viewed export, reject untrusted text beginning with
=,+,-or@after removing leading whitespace/control characters, and reject leading tab/CR/LF controls. Trusted generated numeric fields are distinct from user text. Rejecting such strings is an intentional restriction, not an assertion that apostrophe-prefixing or quoting makes arbitrary CSV universally safe. If lossless text is required, use a typed workbook and verify actual client behavior. - Serve completed files after fresh authorization using
text/csv; charset=utf-8, private caching and a fixed safe attachment filename. Keep paths and opaque artifact ownership server-controlled. Cover expiry, retries, canceled downloads and failed jobs in cleanup. - Remove FastExcel and its provider/facade/config only after all excluded callers have another implementation. Composer may retain OpenSpout if other packages need it; do not remove shared dependencies blindly.
Trial checklist
Parse generated bytes with an independent reader and assert exact headers/rows rather than line counts. Include commas, quotes, Unicode, embedded LF/CRLF/lone CR, null names, empty result, large IDs and leading-zero strings. Verify consumer coercion in the actual importer/spreadsheet; CSV text itself cannot supply spreadsheet cell types.
- Formula-like strings and leading controls trigger the declared restriction without a ready or partially downloadable artifact.
- Distinct tenants cannot export each other's data; all chunks and later downloads reapply authorization.
- Export more than two chunks and prove each expected ID appears once. Concurrent writes follow the declared consistency policy.
- Query, write, flush, close and cancellation failures remove partial files and retain the real error.
- Measure peak memory as row count grows on the real DB driver; check for buffered queries and hidden N+1 access.
Run composer validate --strict, composer audit, the app's test suite and configured static analysis. Record PHP/Laravel versions, dialect, database/filesystem, peak memory and exact outputs with the change.