Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
class Base64Encode extends \php_user_filter
{
private $bufferHandle;
private $tail = '';
public function filter($in, $out, &$consumed, $closing)
{
$data = $this->tail;
while ($bucket = stream_bucket_make_writeable($in)) {
$data .= $bucket->data;
$consumed += $bucket->datalen;
}
$buck = stream_bucket_new($this->bufferHandle, '');
if (false === $buck) {
return PSFS_ERR_FATAL;
}
if (!$closing) {
$dataLen = strlen($data);
$this->tail = substr($data, -1 * ($dataLen % 3));
$buck->data = base64_encode(substr($data, 0, $dataLen - strlen($this->tail)));
} else {
$buck->data = base64_encode($data);
}
stream_bucket_append($out, $buck);
return PSFS_PASS_ON;
}
public function onCreate()
{
$this->bufferHandle = @fopen('php://temp', 'wb+');
return false !== $this->bufferHandle;
}
public function onClose()
{
@fclose($this->bufferHandle);
}
}
stream_filter_register('base64streamEncode', Base64Encode::class);
$filename = '/Volumes/work/LKIM/web/_files/image/da6951bbdf767fef0fd55c869b0cd65d.jpg';
$f = fopen($filename, 'rb+');
stream_filter_append($f, 'base64streamEncode');
$b = '';
while ('' !== $part = stream_get_contents($f, 8192)) {
$b .= $part;
}
fclose($f);
var_dump(number_format(memory_get_peak_usage()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment