PHP - Base64编码大文件并同步回写

PHP - Base64 Encode big files and write back synchronously

我需要用 PHP.
对大文件进行 base64 编码 file()file_get_contents() 不是选项,因为它们将整个文件加载到内存中。
我想到了使用这个:

$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    fclose($handle);
}

来源:Read and parse contents of very large file

这很适合阅读,但是否可以这样做:
读取行 -> base64 编码 -> 写回文件
然后对文件中的每一行重复。
如果它可以直接执行,而不需要写入临时文件,那就太好了。

Base64 将 3 个字节的原始数据编码为 4 个字节的 7 位安全文本。如果你输入少于 3 个字节的填充,你就不能在字符串中间发生这种情况。但是,只要您交易的是 3 的倍数,您就是黄金,sooo:

$base_unit = 4096;
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fread($handle, $base_unit*3)) !== false) {
        echo base64_encode($buffer);
    }
    fclose($handle);
}

http://en.wikipedia.org/wiki/Base64#Examples