Is it possible to code row by row in base64?

2

I have code that takes binary files and converts them to base64, but there are very large files and this ends up using a lot of the machine's memory (and even the process). To read large files usually (without converting them) I do this:

$handle = fopen('ARQUIVO', 'r');

while (FALSE === feof($handle)) {
    $data = fgets($handle);
    ...
}

fclose($handle);

So I avoid exceeding memory and other problems of the genre. But the problem is that with base64_encode I need the complete data (the% with% integer ).

How to encode large binary files without losing performance?

    
asked by anonymous 19.01.2015 / 13:56

1 answer

1

It is possible, yes, the code below has been taken from a comment on the function base64_encode .

$fh = fopen('Input-File', 'rb'); 
//$fh2 = fopen('Output-File', 'wb'); 

$cache = ''; 
$eof = false; 

while (1) { 
    if (!$eof) { 
        if (!feof($fh)) { 
            $row = fgets($fh, 4096); 
        } else { 
            $row = ''; 
            $eof = true; 
        } 
    } 

    if ($cache !== '') 
        $row = $cache.$row; 
    elseif ($eof) 
        break; 

    $b64 = base64_encode($row); 
    $put = ''; 

    if (strlen($b64) < 76) { 
        if ($eof) { 
            $put = $b64."\n"; 
            $cache = ''; 
        } else { 
            $cache = $row; 
        } 

    } elseif (strlen($b64) > 76) { 
        do { 
            $put .= substr($b64, 0, 76)."\n"; 
            $b64 = substr($b64, 76); 
        } while (strlen($b64) > 76); 

        $cache = base64_decode($b64); 

    } else { 
        if (!$eof && $b64{75} == '=') { 
            $cache = $row; 
        } else { 
            $put = $b64."\n"; 
            $cache = ''; 
        } 
    } 

    if ($put !== '') { 
        echo $put; 
        //fputs($fh2, $put); 
        //fputs($fh2, base64_decode($put));
    } 
} 

//fclose($fh2); 
fclose($fh); 
    
19.01.2015 / 14:21