7

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?

6
  • Take a look at this class - it might work: php.net/manual/en/function.base64-encode.php#78765
    – h2ooooooo
    Nov 16, 2012 at 13:50
  • Did you tried to modify the class you found? And could you tell us where is it?
    – SaidbakR
    Nov 16, 2012 at 13:50
  • Removed the comment, my mistake Nov 16, 2012 at 13:53
  • Yes h2ooooooo, that is the class I used. Problem is it acts funny: normal base64_encode() gives me say for string "test": dGVzdA== and with that class (same alphabet) gives me: dGVzdAAA, I need to be identical (with same alphabet, I can change it).
    – bsteo
    Nov 16, 2012 at 13:53
  • @xtmtrx did you include the padding character in the custom alphabet? Nov 16, 2012 at 13:55

2 Answers 2

17

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

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

$encoded = strtr(base64_encode($input), $default, $custom);
4
  • Thought about that but I'm not sure if it achieves valid base64 output?
    – bsteo
    Nov 16, 2012 at 13:56
  • @xtmtrx: I 'm not sure what your intent is here. If you want valid base64 encoding, don't touch the output of base64_encode.
    – Jon
    Nov 16, 2012 at 14:01
  • Using "my alphabed" above ("ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210+/") the encoded string should give me "wTEawZ==" but with the class in h2ooooooo 's example gives me "wTEawZZZ"
    – bsteo
    Nov 16, 2012 at 14:03
  • 4
    @xtmtrx: I really hope you are not using this as "encryption".
    – Jon
    Nov 16, 2012 at 14:08
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.