Last active
August 29, 2015 14:15
-
-
Save sasezaki/3b53b4084630e7ee9078 to your computer and use it in GitHub Desktop.
gently handle memory with ob_start 's callback & StreamableInterface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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