Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

php://memory et maxmemory

By Alexandre Daubois

<?php

// build something entirely in memory...
$fp = fopen('php://memory', 'r+');
fputcsv($fp, ['name', 'email', 'role']);
fputcsv($fp, ['Alex', 'alex@example.com', 'CTO']);
fputcsv($fp, ['Jane', 'jane@example.com', 'Dev']);

rewind($fp);
$csv = stream_get_contents($fp);
fclose($fp);

// send as download
header('Content-Type: text/csv');
echo $csv;

// php://temp, same but spills to disk over 2MB... or more!
$fp = fopen('php://temp/maxmemory:8388608', 'r+');
// 8MB in RAM, then auto-swaps to a temp file

// no gc, no unlink(), no /tmp pollution
// the stream disappears when $fp is closed

php://memory est un flux qui réside en RAM.

php://temp démarre en RAM, déborde sur le disque après 2 Mo (configurable, voir ci-dessous !).

Pas de tmpfile(). Pas de répertoire temporaire. Pas de nettoyage.

Parfait pour construire des fichiers en mémoire avant de les envoyer en PHP !

Connaissiez-vous l’astuce maxmemory ?

See Also

PHP Features

Last updated: 11 October 2026