xZero
xZero

Reputation: 663

PHP - Base64 Encode big files and write back synchronously

I need to base64 encode big file with PHP.
file() and file_get_contents() are not options since them loads whole file into memory.
I got idea to use this:

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

SOURCE: Read and parse contents of very large file

This working well for reading, but is it possible to do it like this:
Read line -> base64 encode -> write back to file
And then repeat for each line in file.
Would be nice if it could do it directly, without need to write to temporary file.

Upvotes: 2

Views: 2084

Answers (1)

Sammitch
Sammitch

Reputation: 32272

Base64 encodes 3 bytes of raw data into 4 bytes on 7-bit safe text. If you feed it less than 3 bytes padding will occur, and you can't have that happen in the middle of the string. However, so long as you're dealing in multiples of 3 you're golden, 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

Upvotes: 3

Related Questions