note 111942 added to function.base64-encode
| From: | HayleyWatson | Date: | Mon, 15 Apr 2013 23:35:51 +0000 |
| Subject: | note 111942 added to function.base64-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-194486@lists.php.net to get a copy of this message | ||
Base64 encoding of large files.
Base64 encoding converts triples of eight-bit symbols into quadruples of six-bit symbols. Reading
the input file in chunks that are a multiple of three bytes in length results in a chunk that can be
encoded independently of the rest of the input file. MIME additionally enforces a line length of 76
characters plus the CRLF. 76 characters is enough for 19 quadruples of six-bit symbols thus
representing 19 triples of eight-bit symbols. Reading 57 eight-bit symbols provides exactly enough
data for a complete MIME-formatted line. Finally, PHP's default buffer size is 8192 bytes -
enough for 143 MIME lines' worth of input.
So if you read from the input file in chunks of 8151 (=57*143) bytes you will get (up to) 8151
eight-bit symbols, which encode as exactly 10868 six-bit symbols, which then wrap to exactly 143
MIME-formatted lines. There is no need to retain left-over symbols (either six- or eight-bit) from
one chunk to the next. Just read a chunk, encode it, write it out, and go on to the next chunk.
Obviously the last chunk will probably be shorter, but encoding it is still independent of the rest.
<?php
while(!feof($input_file))
{
$plain = fread($input_file, 57 * 143);
$encoded = base64_encode($plain);
$encoded = chunk_split($encoded, 76, "\r\n");
fwrite($output_file, $encoded);
}
?>
Conversely, each 76-character MIME-formatted line (not counting the trailing CRLF) contains exactly
enough data for 57 bytes of output without needing to retain leftover bits that need prepending to
the next line. What that means is that each line can be decoded independently of the others, and the
decoded chunks can then be concatenated together or written out sequentially. However, this does
make the assumption that the encoded data really is MIME-formatted; without that assurance it is
necessary to accept that the base64 data won't be so conveniently arranged.
----
Server IP: 103.6.212.224
Probable Submitter: 202.175.135.150
----
Manual Page -- http://php.net/manual/en/function.base64-encode.php
Edit -- https://master.php.net/note/edit/111942
Del: integrated -- https://master.php.net/note/delete/111942/integrated
Del: useless -- https://master.php.net/note/delete/111942/useless
Del: bad code -- https://master.php.net/note/delete/111942/bad+code
Del: spam -- https://master.php.net/note/delete/111942/spam
Del: non-english -- https://master.php.net/note/delete/111942/non-english
Del: in docs -- https://master.php.net/note/delete/111942/in+docs
Del: other reasons-- https://master.php.net/note/delete/111942
Reject -- https://master.php.net/note/reject/111942
Search -- https://master.php.net/manage/user-notes.php