PHP Doku:: Kodiert Daten MIME base64 - function.base64-encode.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige GrunderweiterungenURLsURL Funktionenbase64_encode

Ein Service von Reinhard Neidl - Webprogrammierung.

URL Funktionen




(PHP 4, PHP 5)

base64_encodeKodiert Daten MIME base64


string base64_encode ( string $data )

Kodiert den übergebenene Parameter data mittels base64.

Diese Form des Encodings wurde entworfen, um Binärdaten unbeschädigt mittels Technologien wie E-Mail übertragen zu können, die nicht korrekt mit 8-Bit-Zeichen umgehen.

Base64-kodierte Daten benötigen ungefähr 33% mehr Speicher als die Originaldaten.



Die zu kodierenden Daten.


Die kodierten Daten in Stringform.


Beispiel #1 base64_encode()-Beispiel

'Dies ist ein zu kodierender String';

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:


Siehe auch

34 BenutzerBeiträge:
- Beiträge aktualisieren...
10.09.2010 3:28
output images into html:


= "test.gif";

$handle = fopen($filename, "r");

$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));

'<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" />';


gif - data:image/gif;base64,...
jpg - data:image/jpeg;base64,...
png - data:image/png;base64,...
gustavo at duranlinar dot es
12.01.2010 18:22
Some files can give a real headhache when script file is coded in UTF-8. Change it to ANSI and it'll work fine.
jonb at wobblymusic dot com
6.09.2009 21:21
Note that some applications, such as OpenSSL's enc command, require that there be a line break every 64 characters in order for their base64 decode function to work. The following function will take care of this problem:

function ($encodeMe) {
$data = base64_encode($encodeMe);
$datalb = "";
    while (
strlen($data) > 64) {
$datalb .= substr($data, 0, 64) . "\n";
$data = substr($data,64);
$datalb .= $data;
7.08.2009 23:57
Unfortunately my "function" for encoding base64 on-the-fly from 2007 [which has been removed from the manual in favor of this post] 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:

= 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 (

$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 !== '') {
//fputs($fh2, $put);
        //fputs($fh2, base64_decode($put));        // for comparing

pablo at compuar dot com
31.12.2008 0:46
If you want to send a very long value over URL, you might consider using base64_encode, and discover that IE6 only supports 2000 or so chars.

So, Using a little bit of magic you can do this and be happy:

= 'Blah';

$encoded = strtr(base64_encode(addslashes(gzcompress(serialize($string),9))), '+/=', '-_,');

$string= unserialize(gzuncompress(stripslashes(base64_decode(strtr($encoded, '-_,', '+/=')))));

gglockner AT NOSPAMdwaffler DOT com
20.09.2008 5:21
I omitted the strtr functions in my examples.  Here are corrected functions:

function encode($x) {
strtr(base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x), '+/=', '-_~');

decode($x) {
$y = base64_decode(strtr($x, '-_~', '+/='));
    if (
strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
gglockner AT NOSPAMdwaffler DOT com
19.09.2008 15:35
I have another solution that is simple and elegant.  Create a pseudorandom string of characters.  Then, each time you want to obfuscate your key, append a random substring from the pseudorandom string and use base64 encoding.  When you want to de-obfuscate, convert back from base64.  If the prefix is not in your pseudorandom source, then the value is forged.  Otherwise, strip the prefix and recover your original key.

The advantages are that the string will look different even for the same key, and encoding and decoding should be extremely fast.

Here's an example:


// Call makeCksum once upon landing on the homepage
function makeCksum() {
$str = "";
       for (
$str .= chr(rand(32,126));
$_SESSION['Cksum'] = $str;

encode($x) {
base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x);

decode($x) {
$y = base64_decode($x);
    if (
strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
marcus dot kabele at kabele dot at
3.05.2008 5:22
At Andi:
The last 6 chars of the decoded is used as some checksum + cryptographical salt - this prevents only in/decrementation of a primary key (ID) in an URL.
But there is no obfuscation of the ID, it is visible almost immediately: the number before "-". Hackers are thus guided to this internal ID of the database record and can use this knowledge...

Obfuscate better, making details a little less obvious, but not more secure:
* avoid the "-" (the "checksum/salt" is always the same lenght...),
* obfuscate the integer by converting ist to hex, like the hash.

// unchanged, thanx Tom, Andy, fsx.nr01
function base64_url_encode($input) {
strtr(base64_encode($input), '+/=', '-_,');

base64_url_decode($input) {
base64_decode(strtr($input, '-_,', '+/='));

// some variables are used for clarity, they can be avoided and lines can be shortened:

function encryptId($int, $TableSalt='') {
$GlobalSalt;    // global secret for salt.
$HashedChecksum = substr(sha1($TableSalt.$int.$GlobalSalt), 0, 6);
// The length of the "HashedChecksum" is another little secret,
    // but when the integers are small, it reveals...
$hex = dechex($int);
// The integer is better obfuscated by being HEX like the hash.
return base64url_encode($HashedChecksum.$hex);
// reordered, alternatively use substr() with negative lengths...

decryptId($string, $TableSalt='') {
// checks if the second part of the base64 encoded string is correct.
global $GlobalSalt;    // global secret for salt.
$parts = base64url_decode($string);
$hex = substr($parts, 6);
$int = hexdec($hex);
$part1 = substr($parts, 0, 6);    // The "checksum/salt" is always the same length
return substr(sha1($TableSalt.$int.$GlobalSalt), 0, 6) === $part1
? $int
: false;    // distinguish "0" and "false"

There are some questions remaining:
* Why should we use sha1() for such an low-security task, it needs a lot of calculation.
* Would other algorithms be faster?
If your goal is, to confuse ordinary users, crc32() is much faster than sha1(). (But it can reveal the "salt" which then is much more a filler than a secret.)
If you want to secure against hackers, you should use strong encryption methods instead of obfuscation.

Different approach: these calculations for every URL can be avoided:
Take the database-ID, salt it (with a 'secret'), calculate a hash (like sha1), store it to a (unique - if you don't trust the truncated hash-algorithm any more) column in the database in addition to the primary key, index that field, and use that strange string for the URL and for the query. These calculations are done once and never again, but it costs you more memory for the database.
As secure as the other solution, but much faster (at least for php).
fsx.nr01 [at] gmail [dot] com
14.04.2008 11:56
Shortened the base64url_encode and decode functions from Andi (

function base64_url_encode($input)
    return strtr(base64_encode($input), '+/=', '-_,');

function base64_url_decode($input)
    return base64_decode(strtr($input, '-_,', '+/='));
31.03.2008 23:54
I needed a simple way to obfuscate auto_increment primary keys in databases when they are visible to users in URIs or API calls. The users should not be able to increment the id in the URL and see the next data record in the database table.

My solution (uses modified base64 functions by Tom):

function base64url_encode($plainText) {
    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;  

function base64url_decode($plainText) {
    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;  

function encryptId($int, $class='') {
    return base64url_encode($int.'-'.substr(sha1($class.$int.encryptionKey), 0, 6));

function decryptId($string, $class='') {
    $parts = explode('-', base64url_decode($string));
    if (count($parts) != 2) {
        return 0;
    $int = $parts[0];
    return substr(sha1($class.$int.encryptionKey), 0, 6) === $parts[1]
        ? (int)$int
        : 0;

- The optional 2nd argument is the class name, so two equal ids of different tables will not result in two equal obfuscated ids.

- encryptionKey is a global secret key for encryption.

- decryptId() checks if the second part of the base64 encoded string is correct.
26.02.2008 2:11
a note on URI -safe base64.
Simply replacing + = and / with _ - and . doesn't work as the base64_encode function will insert \r \n chars as well which are not URI-safe. So unless we have a base64encode function that does not insert any newline and padddings, the output can never be URI -safe.

referring to the note posted by " web at pkasperski dot com"

- you might as well use $encoded = strtr ( base64_encode ($data), 'ABCDEFG.....', 'aBcDEfG....' ).

this is more efficient. Also, Is simply changing the casing of the letters  more secure? Why don't you try swapping letters around instead

- for your utf8_encode function, the "ord" function returns  a number in the range 0-255. Remember that strings in PHP are actually a sequence of bytes rather than chars. So your utf8 encode func may not work properly. and the line "for ($n = 0; $n < strlen($input); $n++) {" is inefficient, you should assign  a variable $count to  strlen($input) and use it.

referring to
"dlyaza aT yahoo DOT com"

whats the usefulness of encoding your images in a php file??

referring to  "php at ianco dot co dot uk"

- what version of php are you using? Your code works fine for me. I see all the output.
web at pkasperski dot com
26.10.2007 16: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


class Base64 {
     * I have changed letter placement (P <=> x, S <=> 9) and the cases
     * You can completely redo the mapping table

private static $BinaryMap = array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', //  7
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'x', // 15
'q', 'r', '9', 't', 'u', 'v', 'w', 'x', // 23
'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', // 31
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', // 39
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', // 47
'W', 'P', 'Y', 'Z', '0', '1', '2', '3', // 55
'4', '5', '6', '7', '8', 'S', '+', '/', // 63
'='// padding char
    public function
__construct() {}
    public function
base64_encode($input) {
$output = "";
$chr1 = $chr2 = $chr3 = $enc1 = $enc2 = $enc3 = $enc4 = null;
$i = 0;
//        $input = self::utf8_encode($input);
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]
    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);


and the usage as follows:

= pack('H*', "31c85c5aaa56c1f0102301ea497d0ab010e4e131af261787"); // HEX to binary
echo Base64::base64_encode($string);
"<br />";

and the output will be:

mCHCwQPwWFaqiWhQ9x0kSbdK4tgVjHEh   //  with custom mapping
MchcWqpWwfAQIwHqSX0KsBDk4TGvJheH   //  the base64_encode()
6.12.2006 19:20
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

function base64url_encode($plainText)
$base64 = base64_encode($plainText);
$base64url = strtr($base64, '+/', '-_');
        return (

You may wish to rtrim (or escape) trailing ='s for use in a URI.
eric [at] d512 [dot] com
4.12.2006 4: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.10.2006 14: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
    case 'folder':
        return base64_decode('R0lGODlhEQANAJEDAJmZmf///8zMzP///yH5BAHoAwMALAAAAA
    case 'hidden_file':
        return base64_decode('R0lGODlhEQANAJEDAMwAAP///5mZmf///yH5BAHoAwMALAAAA
    case 'link':
        return base64_decode('R0lGODlhEQANAKIEAJmZmf///wAAAMwAAP///wAAAAAAAAAAA
    case 'smiley':
        return base64_decode('R0lGODlhEQANAJECAAAAAP//AP///wAAACH5BAHoAwIALAAAA
    case 'arrow':
        return base64_decode('R0lGODlhEQANAIABAAAAAP///yH5BAEKAAEALAAAAAARAA0AA
php at ianco dot co dot uk
22.09.2006 17:25
I am finding a length restriction with base64_encode (or possibly with echo) in PHP 4.3.9.
This works ok for me:
echo strlen(str_repeat('-', 3273)); // 3273
echo strlen(base64_encode(str_repeat('-', 3273))); // 4364
echo base64_encode(str_repeat('-', 3273)); // LS0t repeated
But change the length to 3274 and the third echo prints nothing.
echo strlen(str_repeat('-', 3274)); // 3274
echo strlen(base64_encode(str_repeat('-', 3274))); // 4368
echo base64_encode(str_repeat('-', 3274)); // Nothing at all printed
This has obvious implications if you're wanting to encode a fairly large serialized array and echo it to a form field.
peter at mailinator dot com
23.07.2006 23:06
If you want to decode base64 encoded data in Javascript, you can use the tool (Webtoolkit.base64) on this website:
greenthumb at 4point-webdesign dot de
26.04.2006 11: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
28.03.2006 6:06
Just a minor tweak of massimo's functions.

= str_replace(array('+','/','='),array('-','_','.'),$data);
//replace '=' with '.' instead of with nothing, that way the process is reversible.  '.' is uri-safe according to
massimo dot scamarcia at gmail dot com
23.03.2006 16: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.03.2006 12: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.03.2006 22: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 (!
$final .= "A";
$final .= chr($tmp-4);
$start += 6;
    if (
$final .= str_repeat("=",4-strlen($final)%4);

convert_binary_str($string) {
    if (
strlen($string)<=0) return;
$tmp = decbin(ord($string[0]));
$tmp = str_repeat("0",8-strlen($tmp)).$tmp;

conradopinto at yahoo dot com dot br
9.02.2006 16: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
6.12.2005 22: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:

echo base64_encode('<html>');



A function like this could also be useful:

function base64_urlencode($str) {
15.11.2005 6:58
Using base64_encode to produce clean filenames from usernames (e.g. for image upload) is a bad idea if Umlaute (,,) are allowed. Then there is a slash (/) added in the filename, that will lead to a nonexisting directory beeing looked for and your script crashing!
Cristiano Calligaro
25.08.2005 12:05
I've used base64_encode and base64_decode for file attachment both in MySQL (using a BLOB field) and MSSQL (using a TEXT field). For MSSQL remember to set in PHP.INI file both mssql.textsize and mssql.textlimit to 2147483647.

Here's the code:

######### MSSQL(mssql_)/MySQL(mysql_) file attach

$data=base64_encode(addslashes(fread(fopen($val, "r"), filesize($val))));

mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "UPDATE $table SET $field='$data', $fieldname='$valn', $fieldtype='$valt' WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());

######### MSSQL(mssql_)/MySQL(mysql_) open file attached
mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "SELECT $field,$fieldtype FROM $table WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
$row = mssql_fetch_array($result);

header("Content-type: $row[1]");
echo stripslashes(base64_decode($row[0]));

This strategy is good for Microsoft Word, Acrobat PDF, JPG image and so on (even zipped files!!!)
mightymrj at hotmail dot com
28.10.2004 19:35
Problem: mime attachments sending as blank or almost completely blank documents (all data is lost)

Explanation: After a couple days of trying to mime pdf attachments without losing all data, I finally came across this function in some obsolete obscure post:


This is set to on by default in the machine, and it causes fread() and/or base64_encode() (both used in most mime examples I've seen) to read or encrypt binary without slashes for special characters.  This causes sent files to process incorrectly, breaking, thus truncating most of the data in the file. 

Fix: pass 0 to this function and it will do a one time turn off while your code executes.


This can also been turned off in the php.ini file, but I'm not sure what uses that setting or what the consequences might be.

juha at kuhazor dot idlegames dot com
22.06.2004 5:29
If you use base64encoded strings as cookie names, make sure you remove '=' characters. At least Internet Explorer refuses cookie names containing '=' characters or urlencoded cookie names containing %xx character replacements. Use the function below to turn base64 encoded strings to bare alphabets (get rid of / and + characters as well)

function base64clean($base64string)
$base64string = str_replace(array('=','+','/'),'',$base64string);

Siu from Hong Kong
20.11.2003 8:17
As someone suggested above:

using base64_encode() to encode image data and finally output to browser using "data" scheme of IMG src:

// ...
echo '<img src="data:image/png;base64,'.$encoded.' ">';

Netscape browser supports this... However, Windows' Internet Explorer does not.

To embed binary contents in ascii text based html file for IE, you need use MIME multipart.
30.08.2003 0:33
Re the message on 10-May-2003 04:02

You'll want to call urlencode on the base_64 encoded data before putting it into a GET.  IIUC, base 64 output includes the plus and the slash, both of which will be mungered by browsers.
teddy at mycyberclassroom dot com
29.05.2003 6:21
if you want to insert the base64 encoded image in your html <img src> you need to write 'data:datatype;base64,encodeddata' . For example here's a way to embed an PNG image data:

//get the base64 encoded image
$handle = fopen($tempfile,'rb');
$file_content = fread($handle,filesize($tempfile));
$encoded = chunk_split(base64_encode($file_content));

//then echo to browser as:

echo '<img src="data:image/png;base64,'.$encoded.' ">';
Calvin[at] polbox [at] com
13.05.2003 23:34
If you want attach a binary file into mail, pay attention to use mode with "B" flag into fopen function (This is useful only on systems which differentiate between binary and text files, i.e. Windows) Include the 'b' flag in order to make your scripts more portable.

= fopen($source_file,'rb');
$file_content = fread($handle,filesize($source_file));
$encoded = chunk_split(base64_encode($file_content));
koos_nt_hulskamp at hotmail dot com
10.05.2003 14:02
I had to send a php array trough a FORM in HTML, and came up with this solution:

[] = array("foo", "bar");
$coded_array = base64_encode(serialize($array));

now u can put the $coded_array into an input field or even a GET link ex:

<a href="some_script.php?coded_array=<?=$coded_array;?>">script link</a>

after receiving it in the script you send it to, do the following:

= $_GET["coded_array"]     // or $_POST off course
$array = unserialize(base64_decode($coded_array);
guy at bhaktiandvedanta dot com
2.10.2002 2:00
You can use base64_encode to transfer image file into string text and then display them. I used this to store my images in a database and display them form there. First I open the files using fread, encoded the result, and stored that result in the database. Useful for creating random images.



(" Content-Type: image/jpeg");
header(" Content-Disposition: inline");
$sql = "SELECT data FROM image where name='".$img."'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$image = $row[0];


And in the html file you put:

<img src="image.php?img=test3"  border="0" alt="">

Guy Laor

PHP Powered Diese Seite bei
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)