note 96624 added to function.base64-encode

From: Date: Tue, 09 Mar 2010 02:10:40 +0000
Subject: note 96624 added to function.base64-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-166802@lists.php.net to get a copy of this message
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) ---- Server IP: 69.147.83.197 Probable Submitter: 84.170.76.115 ---- Manual Page -- http://www.php.net/manual/en/function.base64-encode.php Edit -- https://master.php.net/note/edit/96624 Del: integrated -- https://master.php.net/note/delete/96624/integrated Del: useless -- https://master.php.net/note/delete/96624/useless Del: bad code -- https://master.php.net/note/delete/96624/bad+code Del: spam -- https://master.php.net/note/delete/96624/spam Del: non-english -- https://master.php.net/note/delete/96624/non-english Del: in docs -- https://master.php.net/note/delete/96624/in+docs Del: other reasons-- https://master.php.net/note/delete/96624 Reject -- https://master.php.net/note/reject/96624 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166802) next »