Created
March 19, 2014 02:09
-
-
Save fasthold/9634254 to your computer and use it in GitHub Desktop.
base62_encode and base62_decode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was taken from my earlier gist