Skip to content

Instantly share code, notes, and snippets.

@the-ge
Forked from mmacia/in_memory_files.php
Created June 26, 2025 13:30
Show Gist options
  • Save the-ge/810a19c805980d319c0d7e668c00377e to your computer and use it in GitHub Desktop.
Save the-ge/810a19c805980d319c0d7e668c00377e to your computer and use it in GitHub Desktop.
Generate files in-memory with PHP
<?php
/**
* This snippet shows a PHP neat trick: build a file into memory without use the filesystem.
*/
$fp = fopen('php://memory', 'rw'); // open an in-memory handler
for ($i = 0; $i < 100; ++$i) { // write some data to handler
fwrite($fp, $i."\n");
}
fseek($fp, 0); // rewind file pointer to the begining
$content = '';
while (!feof($fp)) { // read agian the file handler and put data in a variable
$content .= fread($fp, 8192);
}
fclose($fp); // free allocated memory
echo $content;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment