Skip to content

Instantly share code, notes, and snippets.

@sasezaki
Last active August 29, 2015 14:15
Show Gist options
  • Save sasezaki/3b53b4084630e7ee9078 to your computer and use it in GitHub Desktop.
Save sasezaki/3b53b4084630e7ee9078 to your computer and use it in GitHub Desktop.
gently handle memory with ob_start 's callback & StreamableInterface
<?php
// $ php -d memory_limit=6M ob_start.php
class TempStreamable
{
public $fp;
public function __construct()
{
$OneMB = 1 * 1024 * 1024;
$this->fp = fopen("php://temp/maxmemory:$OneMB", 'r+b');
}
public function write($buffer)
{
return fwrite($this->fp, $buffer);
}
public function getContents()
{
return stream_get_contents($this->fp, -1, 0);
}
}
$streamable = new TempStreamable;
//ob_start(function($buffer) use (&$streamable) {
// $streamable->write($buffer);
//});
ob_start(function($buffer) use (&$streamable) {
$streamable->write($buffer);
}, 1024 * 1024);
// big big response..
foreach (range(0, 9) as $i) {
echo str_repeat($i, 1024 * 1024);
}
ob_end_flush();
echo `ls -la /tmp`; // 10MB temporary file will be created.
// var_dump($streamable->getContents()); // PHP Fatal error: Allowed memory size of 6291456 bytes exhausted (tried to allocate 10493952 bytes)
rewind($streamable->fp); fpassthru($streamable->fp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment