note 96624 deleted from function.base64-encode by danbrown
| From: | danbrown@php.net | Date: | Tue, 09 Mar 2010 04:51:47 +0000 |
| Subject: | note 96624 deleted from function.base64-encode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-166805@lists.php.net to get a copy of this message | ||
Note Submitter: downwind at web dot de
----
I just read MitMacher's note and found his solution pretty pedestrian, extrem slow and the code
hard to understand. Most of the given code does not deal with the problem how to get a chunk
splitted and base64 encoded stream, but with the problem how to handle the fact that we do not know
how much data was read by fgets. So I just wrote some code, which should be easier to understand and
about three times as fast as the given one.
<?php
$hIn = fopen('Input-File', 'rb');
$hOut = fopen('Output-File', 'wb');
if (!$hIn) die("unable to read file");
if (!$hOut) die("unable to write file");
while (($bContent=fread( $hIn, 4104)) != '') {
$sBase64Content = base64_encode($bContent);
// $sOut = chunk_split($sBase64Content, 76, "\n");
$sOut = chunk_split($sBase64Content);
// echo $sOut;
fputs($hOut, $sOut);
}
fclose($hIn);
fclose($hOut);
?>
The output of this script differs from the output of the given script, since this script's
output is rfc2045 conform, which means lines end with \r\n. If you prefer the exact same result as
by the given code, you have to use the other "$sOut = ..." line (which is commented out).
The reason for reading 4104bytes is, that this is a multiple of 57bytes which will result in a
multiple of 76 encoded bytes. That is exactly one line so we never get incomplete lines (except at
eof). We also do not need to care about '=' at the end - since this character will also
only appear in case of eof. (Since in any other case we read a multiple of 3bytes)