note 92762 added to function.base64-encode
| From: | MitMacher at osu1 dot php dot net | Date: | Fri, 07 Aug 2009 21:57:02 +0000 |
| Subject: | note 92762 added to function.base64-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-159197@lists.php.net to get a copy of this message | ||
Unfortunately my "function" for encoding base64 on-the-fly from 2007 (see below) had 2
errors!
The first led to an endless loop because of a missing "$feof"-check, the second caused the
rare mentioned errors when encoding failed for some reason in larger files, especially when
setting fgets($fh, 2) for example. But lower values then 1024 are bad overall because they slow down
the whole process, so 4096 will be fine for all purposes, I guess.
The error was caused by the use of "empty()".
Here comes the corrected version which I have tested for all kind of files and length (up to 4,5
Gb!) without any error:
<?php
$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)); // for comparing
}
}
//fclose($fh2);
fclose($fh);
?>
----
Server IP: 212.124.37.9
Probable Submitter: 91.34.158.69
----
Manual Page -- http://www.php.net/manual/en/function.base64-encode.php
Edit -- https://master.php.net/note/edit/92762
Del: integrated -- https://master.php.net/note/delete/92762/integrated
Del: useless -- https://master.php.net/note/delete/92762/useless
Del: bad code -- https://master.php.net/note/delete/92762/bad+code
Del: spam -- https://master.php.net/note/delete/92762/spam
Del: non-english -- https://master.php.net/note/delete/92762/non-english
Del: in docs -- https://master.php.net/note/delete/92762/in+docs
Del: other reasons-- https://master.php.net/note/delete/92762
Reject -- https://master.php.net/note/reject/92762
Search -- https://master.php.net/manage/user-notes.php