|
|
base64_encode (PHP 3, PHP 4, PHP 5) base64_encode -- Encodes data with MIME base64 Descriptionstring base64_encode ( string data )
base64_encode() returns
data encoded with base64. This encoding
is designed to make binary data survive transport through
transport layers that are not 8-bit clean, such as mail bodies.
Base64-encoded data takes about 33% more space than the original
data.
Пример 1. base64_encode() example |
<?php
$str = 'This is an encoded string';
echo base64_encode($str);
?>
|
This example will produce:
VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw== |
|
See also
base64_decode(),
chunk_split(),
convert_uuencode() and
RFC 2045 section 6.8.
web at pkasperski dot com
26-Oct-2007 07:08
I have implemented the base64_encode() function with some custom mapping table so I could encode some binary data more securely without anyone knowing how to decode it
here is the class
<?php
class Base64 {
private static $BinaryMap = array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'x', 'q', 'r', '9', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'P', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', 'S', '+', '/', '=', );
public function __construct() {}
public function base64_encode($input) {
$output = "";
$chr1 = $chr2 = $chr3 = $enc1 = $enc2 = $enc3 = $enc4 = null;
$i = 0;
while($i < strlen($input)) {
$chr1 = ord($input[$i++]);
$chr2 = ord($input[$i++]);
$chr3 = ord($input[$i++]);
$enc1 = $chr1 >> 2;
$enc2 = (($chr1 & 3) << 4) | ($chr2 >> 4);
$enc3 = (($chr2 & 15) << 2) | ($chr3 >> 6);
$enc4 = $chr3 & 63;
if (is_nan($chr2)) {
$enc3 = $enc4 = 64;
} else if (is_nan($chr3)) {
$enc4 = 64;
}
$output .= self::$BinaryMap[$enc1]
. self::$BinaryMap[$enc2]
. self::$BinaryMap[$enc3]
. self::$BinaryMap[$enc4];
}
return $output;
}
public function utf8_encode($input) {
$utftext = null;
for ($n = 0; $n < strlen($input); $n++) {
$c = ord($input[$n]);
if ($c < 128) {
$utftext .= chr($c);
} else if (($c > 128) && ($c < 2048)) {
$utftext .= chr(($c >> 6) | 192);
$utftext .= chr(($c & 63) | 128);
} else {
$utftext .= chr(($c >> 12) | 224);
$utftext .= chr((($c & 6) & 63) | 128);
$utftext .= chr(($c & 63) | 128);
}
}
return $utftext;
}
}
?>
and the usage as follows:
<?php
$string = pack('H*', "31c85c5aaa56c1f0102301ea497d0ab010e4e131af261787"); echo Base64::base64_encode($string);
echo "<br />";
echo base64_encode($string);
?>
and the output will be:
mCHCwQPwWFaqiWhQ9x0kSbdK4tgVjHEh // with custom mapping
MchcWqpWwfAQIwHqSX0KsBDk4TGvJheH // the base64_encode()
MitMacher
15-Jun-2007 03:28
Recently I have got the problem to sent emails over SMTP with big attachments (up to 16Mb).
Memory_limit is set to 8M, post_max_size and upload_max_filesize are set to 16M, so the file-upload (html-form) does work but the necessary encoding of that file exceeds the memory limit (of course):
<?php
$data = chunk_split(base64_encode(file_get_contents($tmp_file)), 76, "\n");
?>
This is bad, so I searched for a way to do that splitting/encoding stuff on-the-fly (row by row) so that I do not have to keep the whole file data in memory.
Unfortunately I cound not find any function on the web, so I decided to write it on my own and here is the result:
<?php
$fh = fopen('Input-File', 'rb');
$cache = '';
$eof = false;
while (1) {
if (!$eof) {
if (!feof($fh)) {
$row = fgets($fh);
} else {
$row = '';
$eof = true;
}
}
if (!empty($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 ($b64{75} == '=') {
$cache = $row;
} else {
$put = $b64."\n";
$cache = '';
}
}
if (!empty($put)) {
echo $put;
}
}
fclose($fh);
?>
I have tested this (and the decoding!) with several binary and text files up to 1Gb (without echo *g*) and it works great.
The only thing I am wondering about is the read-length of the fgets() function. The default is 1024 which works fine and it should also work with smaller values like 512 or even 2. But this is true only for small files (some kb), the bigger the file the more errors came up.
So the valid minimum seems to be 1024 and maybe more (4096?) on very large files, I dont know.
I have also tested fread() but it works even more worse, I also dont know why...
The other way around it is much more simple: only some base64_decode()s row by row and all has done.
Tom
06-Dec-2006 10:20
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"
<?php
function base64url_encode($plainText)
{
$base64 = base64_encode($plainText);
$base64url = strtr($base64, '+/', '-_');
return ($base64url);
}
?>
You may wish to rtrim (or escape) trailing ='s for use in a URI.
eric [at] d512 [dot] com
03-Dec-2006 07:42
Note that at least some Windows systems will not print a line of characters longer than a certain length unless it has line breaks of some kind. So if you base-64 encode a file, print it back for debugging purposes, and see nothing, don't be alarmed.
dlyaza aT yahoo DOT com
22-Oct-2006 05:57
Using Function:
Output for HTML Put:
<img src="$self?image=file" border="0" alt="file">
<img src="$self?image=folder" border="0" alt="folder">
function getimage ($image) {
switch ($image) {
case 'file':
return base64_decode('R0lGODlhEQANAJEDAJmZmf///wAAAP///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
case 'folder':
return base64_decode('R0lGODlhEQANAJEDAJmZmf///8zMzP///yH5BAHoAwMALAAAAA
ARAA0AAAIqnI+ZwKwbYgTPtIudlbwLOgCBQJYmCYrn+m3smY5v
Gc+0a7dhjh7ZbygAADsA');
case 'hidden_file':
return base64_decode('R0lGODlhEQANAJEDAMwAAP///5mZmf///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
case 'link':
return base64_decode('R0lGODlhEQANAKIEAJmZmf///wAAAMwAAP///wAAAAAAAAAAA
CH5BAHoAwQALAAAAAARAA0AAAM5SArcrDCCQOuLcIotwgTYUll
NOA0DxXkmhY4shM5zsMUKTY8gNgUvW6cnAaZgxMyIM2zBLCaHlJgAADsA');
case 'smiley':
return base64_decode('R0lGODlhEQANAJECAAAAAP//AP///wAAACH5BAHoAwIALAAAA
AARAA0AAAIslI+pAu2wDAiz0jWD3hqmBzZf1VCleJQch0rkdnppB3
dKZuIygrMRE/oJDwUAOwA=');
case 'arrow':
return base64_decode('R0lGODlhEQANAIABAAAAAP///yH5BAEKAAEALAAAAAARAA0AA
AIdjA9wy6gNQ4pwUmav0yvn+hhJiI3mCJ6otrIkxxQAOw==');
}
}
php at ianco dot co dot uk
22-Sep-2006 08:25
I am finding a length restriction with base64_encode (or possibly with echo) in PHP 4.3.9.
This works ok for me:
<?php
echo strlen(str_repeat('-', 3273)); echo strlen(base64_encode(str_repeat('-', 3273))); echo base64_encode(str_repeat('-', 3273)); ?>
But change the length to 3274 and the third echo prints nothing.
<?php
echo strlen(str_repeat('-', 3274)); echo strlen(base64_encode(str_repeat('-', 3274))); echo base64_encode(str_repeat('-', 3274)); ?>
This has obvious implications if you're wanting to encode a fairly large serialized array and echo it to a form field.
greenthumb at 4point-webdesign dot de
26-Apr-2006 02:57
I had massive problems storing a serialized Object which contained UTF-8 parts and some ascii parts (from the serialization i think) into mysql.
So i used base64_encode to get a clean string which could be safely decoded and unserialized.
this is bulletproof - if you ever have trouble use this.
the runtime is imho no problem.
dawgeatschikin at hotmail dot com
27-Mar-2006 08:06
Just a minor tweak of massimo's functions.
<?
$data = str_replace(array('+','/','='),array('-','_','.'),$data);
//replace '=' with '.' instead of with nothing, that way the process is reversible. '.' is uri-safe according to http://www.w3.org/Addressing/URL/5_URI_BNF.html
?>
massimo dot scamarcia at gmail dot com
23-Mar-2006 07:23
$data = str_replace(array('+','/','='),array('-','_',),$data); // MIME::Base64::URLSafe implementation
$data = str_replace(array('+','/'),array('-','_'),$data); // Python raise "TypeError: Incorrect padding" if you remove "=" chars when decoding
massimo dot scamarcia at gmail dot com
23-Mar-2006 03:02
function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
function urlsafe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
Php version of perl's MIME::Base64::URLSafe, that provides an url-safe base64 string encoding/decoding (compatible with python base64's urlsafe methods)
Gabriel Malca
17-Mar-2006 01:45
If the function doesn't exist, this is a messy but effective way of doing it:
<?
echo bencode("Gabriel Malca");
// R2FicmllbCBNYWxjYQ==
function bencode($string='') {
$binval = convert_binary_str($string);
$final = "";
$start = 0;
while ($start < strlen($binval)) {
if (strlen(substr($binval,$start)) < 6)
$binval .= str_repeat("0",6-strlen(substr($binval,$start)));
$tmp = bindec(substr($binval,$start,6));
if ($tmp < 26)
$final .= chr($tmp+65);
elseif ($tmp > 25 && $tmp < 52)
$final .= chr($tmp+71);
elseif ($tmp == 62)
$final .= "+";
elseif ($tmp == 63)
$final .= "/";
elseif (!$tmp)
$final .= "A";
else
$final .= chr($tmp-4);
$start += 6;
}
if (strlen($final)%4>0)
$final .= str_repeat("=",4-strlen($final)%4);
return $final;
}
function convert_binary_str($string) {
if (strlen($string)<=0) return;
$tmp = decbin(ord($string[0]));
$tmp = str_repeat("0",8-strlen($tmp)).$tmp;
return $tmp.convert_binary_str(substr($string,1));
}
?>
conradopinto at yahoo dot com dot br
09-Feb-2006 07:04
There is an error on the example of passing an array through an HTML Form.
In the line:
$array = unserialize(base64_decode($coded_array);
There is a ')' missing. it should be:
$array = unserialize(base64_decode($coded_array));
virtuall at virtuall dot info
06-Dec-2005 01:53
If you encode text that contains symbols like < > and want to send it in GET query, be sure to urlencode the result of base64_encode, as it sometimes adds a + (and it's a special symbol) at the end:
<?php
echo base64_encode('<html>');
?>
returns:
PGh0bWw+
A function like this could also be useful:
<?php
function base64_urlencode($str) {
return urlencode(base64_encode($str));
};
?>
andi151278
14-Nov-2005 09:58
Using base64_encode to produce clean filenames from usernames (e.g. for image upload) is a bad idea if Umlaute (
|
|
|