public
Last active

Output buffer for large output to temporary file on disk (>2MB)

  • Download Gist
output-buffer-to-temp.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
<?php
/*
* Output buffer for large output to temporary file on disk (>2MB)
*
* @link http://stackoverflow.com/questions/5446647/how-can-i-use-var-dump-output-buffering-without-memory-errors/
*/
 
/**
* Iterate over lines of a stream resource.
*
* Note: ResourceIterator is a NoRewindIterator on non-seekable streams.
*/
class StreamIterator implements Iterator
{
private $handle;
private $current;
private $index = 0;
 
public function __construct($handle) {
$this->handle = $handle;
}
 
public function current() {
return $this->current;
}
 
public function next() {
$this->index++;
$this->current = fgets($this->handle);
}
 
public function key() {
return $this->index;
}
 
public function valid() {
return $this->current !== FALSE;
}
 
public function rewind() {
$this->index = 0;
$meta = stream_get_meta_data($this->handle);
$meta['seekable'] && fseek($this->handle, 0);
$this->next();
}
}
 
/**
* Interface of a Store for Buffering
*
* (subset of SplFileObject/SplTempFileObject that was originally used)
*/
interface BufferStore
{
public function fseek($offset, $whence = SEEK_SET);
 
public function ftruncate($size);
 
public function ftell();
 
public function fwrite($string, $length = null);
}
 
/**
* Stream (Stream I/O)
*/
class StreamObject implements BufferStore, IteratorAggregate
{
private $handle;
 
public function __construct($handle) {
$this->handle = $handle;
}
 
public function fseek($offset, $whence = SEEK_SET) {
fseek($this->handle, $offset, $whence);
}
 
public function ftruncate($size) {
ftruncate($this->handle, $size);
}
 
public function ftell() {
return ftell($this->handle);
}
 
public function fwrite($string, $length = null) {
if ($length === null) {
return fwrite($this->handle, $string);
}
 
return fwrite($this->handle, $string, $length);
}
 
public function getHandle() {
return $this->handle;
}
 
public function getUri() {
$meta = stream_get_meta_data($this->handle);
return $meta['uri'];
}
 
public function getIterator() {
return new StreamIterator($this->handle);
}
}
 
/**
* Uri (Stream I/O)
*/
class UriObject extends StreamObject
{
public function __construct($uri) {
parent::__construct(fopen($uri, 'r+'));
}
}
 
/**
* Buffer to temporary location if larger than 2 MB
*/
class OutputBuffer
{
/**
* @var int
*/
private $chunkSize;
 
/**
* @var bool
*/
private $started;
 
/**
* @var SplFileObject
*/
private $store;
 
/**
* @var int
*/
private $bufferedCounter;
 
/**
* @var bool Set Verbosity to true to output analysis data to stderr
*/
private $verbose = true;
 
public function __construct($chunkSize = 1024) {
$this->chunkSize = $chunkSize;
$this->store = new UriObject('php://temp');
}
 
public function start() {
if ($this->started) {
throw new BadMethodCallException('Buffering already started, can not start again.');
}
$this->started = true;
$this->bufferedCounter = 0;
$result = ob_start(array($this, 'bufferCallback'), $this->chunkSize);
$this->verbose && file_put_contents('php://stderr', sprintf("Starting Buffering: %d; Level %d\n", $result, ob_get_level()));
return $result;
}
 
public function flush() {
$this->started && ob_flush();
}
 
public function stop() {
if ($this->started) {
ob_flush();
$result = ob_end_flush();
$this->started = false;
$this->verbose && file_put_contents('php://stderr', sprintf("Buffering stopped: %d; Level %d\n", $result, ob_get_level()));
}
}
 
private function bufferCallback($chunk, $flags) {
 
$chunkSize = strlen($chunk);
 
if ($this->verbose) {
$level = ob_get_level();
$constants = [
'PHP_OUTPUT_HANDLER_START', 'PHP_OUTPUT_HANDLER_WRITE', 'PHP_OUTPUT_HANDLER_FLUSH',
'PHP_OUTPUT_HANDLER_CLEAN', 'PHP_OUTPUT_HANDLER_FINAL'
];
 
$flagsText = '';
foreach ($constants as $i => $constant) {
if ($flags & ($value = constant($constant)) || $value == $flags) {
$flagsText .= (strlen($flagsText) ? ' | ' : '') . $constant . "[$value]";
}
}
 
$total = $this->bufferedCounter;
 
file_put_contents(
'php://stderr', sprintf(
"Buffer Callback: Chunk Size %s; Total %s; Flags %s (%s); Level %d\n",
number_format($chunkSize), number_format($total + $chunkSize), $flags, $flagsText, $level
)
);
}
 
if ($flags & PHP_OUTPUT_HANDLER_FINAL) {
return TRUE;
}
 
if ($flags & PHP_OUTPUT_HANDLER_START) {
$this->store->fseek(0, SEEK_END);
}
 
$chunkSize && $this->store->fwrite($chunk);
$this->bufferedCounter += $chunkSize;
 
if ($flags & PHP_OUTPUT_HANDLER_FLUSH) {
// there is nothing to d
}
 
if ($flags & PHP_OUTPUT_HANDLER_CLEAN) {
$this->store->ftruncate(0);
}
 
return "";
}
 
public function getSize() {
$this->store->fseek(0, SEEK_END);
return $this->store->ftell();
}
 
public function getBufferFile() {
return $this->store;
}
 
public function getBuffer() {
$array = iterator_to_array($this->store);
return implode('', $array);
}
 
public function __toString() {
return $this->getBuffer();
}
 
public function endClean() {
return ob_end_clean();
}
}
 
$buffer = new OutputBuffer(); # 16384
echo "Starting Buffering now.\n=======================\n";
$buffer->start();
 
$var = [];
foreach (range(1, 30) as $iteration) {
$array = [];
foreach (range(1, 30) as $iteration) {
$array2 = [];
foreach (range(1, 12) as $iteration) {
$array2[] = range(1, 100);
}
$array[] = $array2;
}
$var[] = $array;
}
print_r($var);
$buffer->stop();
 
echo "Buffering Results:\n==================\n";
$size = $buffer->getSize();
echo "Buffer Size: ", number_format($size), "\n";
echo "Memory Used: ", number_format(memory_get_usage(true)), "\n";
echo "Maximum Memory: ", ini_get('memory_limit'), "\n";
echo "String length: ", strlen($buffer), ".\n"; // this will break the 128M limit then
echo "Peeking into buffer: ", var_dump(substr($buffer, 0, 10)), ' ...', var_dump(substr($buffer, -10)), "\n";
sleep(10); // some time left to take a look into the tempdir for the buffer

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.