Skip to content

Instantly share code, notes, and snippets.

@fasthold
Created March 19, 2014 02:09
Show Gist options
  • Save fasthold/9634254 to your computer and use it in GitHub Desktop.
Save fasthold/9634254 to your computer and use it in GitHub Desktop.
base62_encode and base62_decode
<?php
// from http://encode-base62.nichabi.com/php-function.php
function base62_encode ($data) {
$outstring = '';
$len = strlen($data);
for ($i = 0; $i < $len; $i += 8) {
$chunk = substr($data, $i, 8);
$outlen = ceil((strlen($chunk) * 8) / 6);
$x = bin2hex($chunk);
$w = gmp_strval(gmp_init(ltrim($x, '0'), 16), 62);
$pad = str_pad($w, $outlen, '0', STR_PAD_LEFT);
$outstring .= $pad;
}
return $outstring;
}
// from http://decode-base62.nichabi.com/php-function.php
function base62_decode ($data) {
$outstring = '';
$len = strlen($data);
for ($i = 0; $i < $len; $i += 11) {
$chunk = substr($data, $i, 11);
$outlen = floor((strlen($chunk) * 6) / 8);
$y = gmp_strval(gmp_init(ltrim($chunk, '0'), 62), 16);
$pad = str_pad($y, $outlen * 2, '0', STR_PAD_LEFT);
$outstring .= pack('H*', $pad);
}
return $outstring;
}
@Synchro
Copy link

Synchro commented Jun 13, 2018

This was taken from my earlier gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment