Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP base64 encoding custom alphabet

Tags:

php

I try to use base64_encode() and base64_decode() but with custom alphabet. Default alphabet is:

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

say I want to use:

"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210+/" 

found a class on internet but doesn't work as expected. Any idea on how to achieve this as simple as possible?

like image 976
bsteo Avatar asked Nov 16 '12 13:11

bsteo


People also ask

How do you Base64 encode 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. The base64_encoded data takes 33% more space then original data.

Can Base64 have slashes?

No. The Base64 alphabet includes A-Z, a-z, 0-9 and + and / .

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 I use base64decode?

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.


2 Answers

Ultra easy, strtr can do this out of the box:

$default = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
$custom  = "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210+/";

$encoded = strtr(base64_encode($input), $default, $custom);
like image 200
Jon Avatar answered Sep 22 '22 00:09

Jon


In addition to the custom encoding defined above, to decode with a custom alphabet, you can do the following:

    $custom = 'ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210+/';
    $default = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    $decoded = base64_decode(strtr($input, $custom, $default));
like image 33
crockwave Avatar answered Sep 21 '22 00:09

crockwave