PHP Base62 Sample Code

Access PHP code examples to implement Base62 encoding and decoding functionality in your web applications.

<?php

class Base62 {
    private static $BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

    public static function encode($input) {
        if (strlen($input) === 0) {
            return '';
        }

        $value = new \GMP(bin2hex($input), 16);
        $result = '';

        while (gmp_cmp($value, 0) > 0) {
            list($value, $remainder) = gmp_div_qr($value, 62);
            $result .= self::$BASE62[gmp_intval($remainder)];
        }

        for ($i = 0; $i < strlen($input); $i++) {
            if ($input[$i] === "\0") {
                $result .= self::$BASE62[0];
            } else {
                break;
            }
        }

        return strrev($result);
    }

    public static function decode($input) {
        if (strlen($input) === 0) {
            return '';
        }

        $value = new \GMP(0);
        for ($i = 0; $i < strlen($input); $i++) {
            $value = gmp_add(gmp_mul($value, 62), strpos(self::$BASE62, $input[$i]));
        }

        $hex = gmp_strval($value, 16);
        if (strlen($hex) % 2 !== 0) {
            $hex = '0' . $hex;
        }

        $bytes = hex2bin($hex);
        $leadingZeroes = 0;
        for ($i = 0; $i < strlen($input); $i++) {
            if ($input[$i] === self::$BASE62[0]) {
                $leadingZeroes++;
            } else {
                break;
            }
        }

        return str_repeat("\0", $leadingZeroes) . $bytes;
    }
}

// Usage
$input = "回□〓≡╝╚╔╗";
$encoded = Base62::encode($input);
echo "Encoded: $encoded\n";

$decoded = Base62::decode($encoded);
echo "Decoded: $decoded\n";
?>
Base62 Sample Code