0

I need custom implementation (library or set of classes/functions) of Base32 or Base64 in PHP

Function should return URL safe strings.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
I-M-JM
  • 15,732
  • 26
  • 77
  • 103

2 Answers2

2

Since you don't have access to base64 build in function I suggest you this :

<?php

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 (!$tmp)
            $final .= "A";
        else
            $final .= chr($tmp-4);
        $start += 6;
    }
    if (strlen($final)%4>0)
        $final .= str_repeat("=",4-strlen($final)%4);
    return $final;
}

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

?>
David Bélanger
  • 7,400
  • 4
  • 37
  • 55
  • This is the only correct answer. This question shouldn't be modded down - base64_ functions can be disabled on some hosts because of security concerns. Yes, it pretty much cripples a standard PHP install, but there are times when it's worth having the built in functions disabled. – John Hunt Aug 17 '15 at 09:26
  • @JohnHunt this is not correct either as it's not URL safe. – Jon Grant Aug 19 '15 at 08:52
  • 1
    @JonGrant And that's why `urlencode` and `urldecode` exists sir. – David Bélanger Aug 19 '15 at 15:59
-1

I would use these functions to make strings URL safe.

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

function base64_url_decode($input) {
 return base64_decode(strtr($input, '-_,', '+/='));
}
Xeoncross
  • 55,620
  • 80
  • 262
  • 364