Php encode and decode string

(PHP 4, PHP 5, PHP 7, PHP 8)

base64_encodeEncodes data with MIME base64

Description

base64_encode(string $string): string

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.

Parameters

string

The data to encode.

Return Values

The encoded data, as a string.

Examples

Example #1 base64_encode() example

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

The above example will output:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

See Also

  • base64_decode() - Decodes data encoded with MIME base64
  • chunk_split() - Split a string into smaller chunks
  • convert_uuencode() - Uuencode a string
  • » RFC 2045 section 6.8

gutzmer at usa dot net

11 years ago

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

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

Rasmus Schultz

4 years ago

In PHP 7, the padding issue with base64_decode() is no more - the following is totally fine:

function base64_encode_url($string) {
    return str_replace(['+','/','='], ['-','_',''], base64_encode($string));
}

function base64_decode_url($string) {
    return base64_decode(str_replace(['-','_'], ['+','/'], $string));
}

Checked here with random_bytes() and random lengths:

https://3v4l.org/aEs4o

biziclop at vipmail dot hu

4 years ago

gutzmer at usa dot net's ( http://php.net/manual/en/function.base64-encode.php#103849 ) base64url_decode() function doesn't pad longer strings with '='s. Here is a corrected version:

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

function

base64url_decode( $data ){
  return
base64_decode( strtr( $data, '-_', '+/') . str_repeat('=', 3 - ( 3 + strlen( $data )) % 4 ));
}
// proof
for( $i = 0, $s = ''; $i < 24; ++$i, $s .= substr("$i", -1 )){
 
$base64_encoded    = base64_encode(    $s );
 
$base64url_encoded = base64url_encode( $s );
 
$base64url_decoded = base64url_decode( $base64url_encoded );
 
$base64_restored   = strtr( $base64url_encoded, '-_', '+/')
                     .
str_repeat('=',
                        
3 - ( 3 + strlen( $base64url_encoded )) % 4
                      
);
  echo
"$s
$base64url_decoded
$base64_encoded
$base64_restored
$base64url_encoded

"
;
}
?>

MitMacher

13 years ago

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:

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

Hayley Watson

9 years ago

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.

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.

luke at lukeoliff.com

11 years ago

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.

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

or

Php encode and decode string

massimo dot scamarcia at gmail dot com

16 years ago

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)

Naser Mirzaei

8 years ago

$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 "';?>

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

virtuall at virtuall dot info

16 years ago

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

returns:

PGh0bWw+

A function like this could also be useful:

    function base64_urlencode($str) {
        return
urlencode(base64_encode($str));
    };
?>

eric [at] d512 [dot] com

15 years ago

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.

sadhooklay [at] gmail [dot] com

7 years ago

    /**
     * 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), '+/', '-_'), '=');
    }
?>

gglockner AT NOSPAMdwaffler DOT com

14 years ago

I omitted the strtr functions in my examples.  Here are corrected functions:

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

function

decode($x) {
   
$y = base64_decode(strtr($x, '-_~', '+/='));
    if (
strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
    return
substr($y,4-strlen($y));
}
?>

dlyaza aT yahoo DOT com

15 years ago

Using Function:
Output for HTML Put:

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==');
    }
}

guy at bhaktiandvedanta dot com

20 years ago

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.

image.php:

header(" 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];
echo base64_decode($image);

?>

And in the html file you put:

Guy Laor

divinity76 at gmail dot com

1 year ago

if you for some reason need a base10 / pure-number encode instead, encoding to some combination of 0123456789

// base10-encode using the dictionary 0123456789
function base10_encode(string $str): string
{
   
$ret = "";
    for (
$i = 0, $imax = strlen($str); $i < $imax; ++ $i) {
       
$ret .= str_pad((string) ord($str[$i]), 3, "0", STR_PAD_LEFT);
    }
    return
$ret;
}
// base10-decode using the dictionary 0123456789
function base10_decode(string $str): string
{
   
$ret = "";
    for (
$i = 0, $imax = strlen($str); $i < $imax; $i += 3) {
       
// notably here we are using (int) to trim away the zeroes..
       
$ret .= chr((int) substr($str, $i, 3));
    }
    return
$ret;
}
?>

it is unicode-safe and binary-safe, testing:

// simple ascii test:
$d=[];
$d["raw"]="test";
$d["b10"]=base10_encode($d["raw"]); // 116101115116
$d["decoded"]=base10_decode($d["b10"]); // test
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false
var_dump($d);
// complex unicode test:
$d=[];
$d["raw"]="ˈmaʳkʊs kuːn ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (A ⇔ B), Σὲ γνωρίζω ἀπὸ τὴν κόψη Οὐχὶ ταὐτὰ παρίσταταί გთხოვთ ሰማይ አይታረስ ንጉሥ አይከሰስ ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ ";
// lets add some chess for good measure
$d["raw"].="♔♕♖♗♘♙♚♛♜♝♞🙾🙿";
$d["b10"]=base10_encode($d["raw"]); //
$d["decoded"]=base10_decode($d["b10"]);
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false, base10 is unicode safe :D
var_dump($d);
// binary safety test:
$everything="";
for(
$i=0;$i<=0xFF;++$i){
   
$everything.=chr($i);
}
$d=[];
$d["raw"]=$everything;
$d["b10"]=base10_encode($d["raw"]);
$d["decoded"]=base10_decode($d["b10"]);
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false :D base10 is binary safe.
var_dump($d);?>

raat1979 at gmail dot com

4 years ago

shortest base64url_decode (correct version)

    function base64_urldecode($data){
        return
base64_decode(strtr($data,'-_','+/').str_repeat("=", -strlen($data) & 3));
}
?>

gglockner AT NOSPAMdwaffler DOT com

14 years ago

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 (
$i=0;$i<32;++$i)
              
$str .= chr(rand(32,126));
      
$_SESSION['Cksum'] = $str;
}

function

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

function

decode($x) {
   
$y = base64_decode($x);
    if (
strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
    return
substr($y,4-strlen($y));
}
?>

Anonymous

7 years ago

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:

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:

$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, "._-");
?>

raat1979 at gmail dot com

4 years ago

shortest base64url_decode

function base64url_decode($data){
        return
base64_decode($data.str_repeat("=", -strlen($data) & 3));
}
?>

d_maksimov at inbox dot ru

1 year ago

You can escape '+', '/' and '=' symbols using two simple functions:

function base_encode($id) {
    return
str_replace(["A", "+", "/", "="], ["AA", "AB", "AC", "AD"], base64_encode($id));
}

function

base_decode($id) {
   
$id = preg_replace_callback('/(AA)|(AB)|(AC)|(AD)/', function ($m) {
        foreach([
'A', '+', '/', '='] as $i => $value)
            if(
$m[$i + 1])
                return
$value;
    },
$id);
    return
base64_decode($id);
}
?>

this functions escapes symbol 'A' as 'AA', '+' as 'AB', '/' as 'AC', '=' as 'AD'.

What is encoding and decoding PHP?

Encoding and decoding URL strings are used to convert general URL strings and characters into an arrangement that can be conveyed over the internet. In this tutorial, you will learn about two ways in which URL string can be encoded and decoded in PHP.

Can you encode a string in PHP?

The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64.

What is base64 decode in PHP?

The base64_decode() is an inbuilt function in PHP which is used to Decodes data which is encoded in MIME base64. Syntax: string base64_decode( $data, $strict ) Parameters: This function accepts two parameter as mentioned above and described below: $data: It is mandatory parameter which contains the encoded string.

How do you base64 encode in PHP?

Syntax. base64_encode() function can encode 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 can take about 33% more space than original data.