Documentation on base64_encode

base64_encode = Encodes data with MIME base64

Encodes the given data 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.

Usage, params, and more on base64_encode

string base64_encode ( string $data )

data The data to encode.

The encoded data, as a string or FALSE on failure.

Notes and warnings on base64_encode

Basic example of how to use: base64_encode

Example #1 base64_encode() example

<?php
$str 
'This is an encoded string';
echo 
base64_encode($str);
?>

The above example will output:

 VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw== 

Other code examples of base64_encode being used

For anyone interested in the 'base64url' variant encoding, you can use this pair of functions:

<?php
function base64url_encode($data) {
  return
rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function
base64url_decode($data) {
  return
base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
?>

Base64 encoding of large files.

Base64 encoding converts triples of eight-bit symbols into quadruples of six-bit symbols. Reading the input file in chunks that are a multiple of three bytes in length results in a chunk that can be encoded independently of the rest of the input file. MIME additionally enforces a line length of 76 characters plus the CRLF. 76 characters is enough for 19 quadruples of six-bit symbols thus representing 19 triples of eight-bit symbols. Reading 57 eight-bit symbols provides exactly enough data for a complete MIME-formatted line. Finally, PHP's default buffer size is 8192 bytes - enough for 143 MIME lines' worth of input.

So if you read from the input file in chunks of 8151 (=57*143) bytes you will get (up to) 8151 eight-bit symbols, which encode as exactly 10868 six-bit symbols, which then wrap to exactly 143 MIME-formatted lines. There is no need to retain left-over symbols (either six- or eight-bit) from one chunk to the next. Just read a chunk, encode it, write it out, and go on to the next chunk. Obviously the last chunk will probably be shorter, but encoding it is still independent of the rest.

<?php

while(!feof($input_file))
{
   
$plain = fread($input_file, 57 * 143);
   
$encoded = base64_encode($plain);
   
$encoded = chunk_split($encoded, 76, "\r\n");
   
fwrite($output_file, $encoded);
}

?>

Conversely, each 76-character MIME-formatted line (not counting the trailing CRLF) contains exactly enough data for 57 bytes of output without needing to retain leftover bits that need prepending to the next line. What that means is that each line can be decoded independently of the others, and the decoded chunks can then be concatenated together or written out sequentially. However, this does make the assumption that the encoded data really is MIME-formatted; without that assurance it is necessary to accept that the base64 data won't be so conveniently arranged.

A function I'm using to return local images as base64 encrypted code, i.e. embedding the image source into the html request.

This will greatly reduce your page load time as the browser will only need to send one server request for the entire page, rather than multiple requests for the HTML and the images. Requests need to be uploaded and 99% of the world are limited on their upload speed to the server.

<?php
function base64_encode_image ($filename=string,$filetype=string) {
    if (
$filename) {
       
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return
'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}
?>

used as so

<style type="text/css">
.logo {
    background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px;
}
</style>

or

<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/>

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:

<?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);
?>

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.

An even faster way to line-breaks every 64th character is using the chunk_split function:

<?php
$string
= chunk_split(base64_encode($string), 64, "\n");
?>

@gutzmer at usa dot net

Nice idea! However...

The function base64url_decode doesn't pad strings longer than 4 chars.
str_pad will only pad the string if the second argument is larger than the length of the original string. So the correct function should be:

<?php
function base64url_decode($data) {
 
$len = strlen($data);
  return
base64_decode(str_pad(strtr($data, '-_', '+/'), $len + $len % 4, '=', STR_PAD_RIGHT));
}

Note that base64_decode works fine without the padding, that is why your function works.

Wikipedia has a list of 8 or so variations on the last 2 characters in Base64  (https://en.wikipedia.org/wiki/Base64). The following functions can handle all of them:

<?php
function base64_encode2($data, $a = "+/=") {
   
$l = strlen($a);
    if (
$l === 3) {
        return
strtr(base64_encode($data), "+/=", $a);
    } else if (
$l === 2) {
        return
rtrim(strtr(base64_encode($data), "+/", $a), '=');
    } else {
        throw new
InvalidArgumentException("Argument #2 must be 2 or 3 bytes.");
    }
}

function
base64_decode2($data, $strict = false, $a = "+/=") {
   
$l = strlen($a);
    if (
$l === 3) {   
        return
base64_decode(strtr($data, $a, "+/="), $strict);
    } else if (
$l === 2) {
        return
base64_decode(strtr($data, $a, "+/"), $strict);
    } else {
        throw new
InvalidArgumentException("Argument #2 must be 2 or 3 bytes.");
    }
}
?>

Example usage:

<?php
$decoded
= "ABC123";

// base64 XML identifier:
$encoded = base64_encode2($decoded, "_:");
$decoded = base64_decode2($encoded, false, "_:");

// base64 URL (RFC 6920):
// base64 XML name token:
$encoded = base64_encode($decoded, "-_")
$decoded = base64_decode($encoded, false, "-_");

// modified base64 XML name token:
$encoded = base64_encode2($decoded, ".-");
$decoded = base64_decode2($encoded, false, ".-");

// modified base64 for Regular Expressions:
$encoded = base64_encode2($decoded, "!-");
$decoded = base64_decode2($encoded, false, "!-");

// base64 used in YUI library:
$encoded = base64_encode2($decoded, "._-");
$decoded = base64_decode2($encoded, false, "._-");
?>

<?php
   
/**
     * Generates a random URL-safe base64 string.
     *
     * See RFC 3548 for the definition of URL-safe base64.
     * If $n is not specified, Secure::RANDOM_LENGTH is assumed. It may be larger in future.
     *
     * @param int $n Specifies the length of the random string
     * @param bool $padding
     * @return string The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true.
     */
   
public static function newToken($n = null, $padding = false)
    {
       
// Generate a new unique token
       
if (!function_exists('openssl_random_pseudo_bytes')) {
           
// Generate a random pseudo bytes token if openssl_random_pseudo_bytes is available
            // This is more secure than uniqid, because uniqid relies on microtime, which is predictable
           
$s = pack('a*', openssl_random_pseudo_bytes($n ?: static::RANDOM_LENGTH));
           
$s = str_replace(["\n", "\r", "\n\r"], '', $s);
        } else {
           
// Otherwise, fall back to a hashed uniqid
           
$s = substr(hash('sha256', uniqid(null, true)), 0, $n ?: static::RANDOM_LENGTH);
        }

        return
$padding ? strtr(base64_encode($s), '+/', '-_') : rtrim(strtr(base64_encode($s), '+/', '-_'), '=');
    }
?>

<?php
$image
= 'example.png';

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo "<img src=\"$src\" alt=\"\" />";
?>

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)

<?php
function base64clean($base64string)
{
    
$base64string = str_replace(array('=','+','/'),'',$base64string);

     return
$base64string;
}
?>

output images into html:

<?php

$imgfile
= "test.gif";

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

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

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

?>

gif - data:image/gif;base64,...
jpg - data:image/jpeg;base64,...
png - data:image/png;base64,...
etc.