Skip to content

Instantly share code, notes, and snippets.

@goncalomb goncalomb/base62.php
Last active Feb 19, 2016

Embed
What would you like to do?
Integer to/from Base62 in PHP
<?php
// Author: Gonçalo Baltazar <me@goncalomb.com>
// I place this code in the public domain.
/**
* Functions to encode/decode an integer to/from base62.
* It is limited to positive integers up to BASE62_MAX to make sure it works on
* 32-bit systems.
*/
// You can change BASE62_CHARS but keep it 62 characters long.
define('BASE62_CHARS', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
define('BASE62_MAX', 2147483647);
define('BASE62_MAX_5CHARS', 916132831);
/**
* Encode int to base62.
* By default it returns a string padded to 5 characters. If encoding a number
* bigger than BASE62_MAX_5CHARS the string will have 6 characters.
* Change the default padding with $pad.
*/
function int_to_base62($num, $pad=5) {
$n = (int) $num;
if ($num != $n || $n < 0 || $n > BASE62_MAX) {
// invalid int
return null;
}
$chars = BASE62_CHARS;
$str = '';
do {
$str = $chars[$n%62] . $str;
$n = floor($n/62);
} while ($n > 0);
return ($pad && $pad > 0 ? str_pad($str, ($pad > 6 ? 6 : $pad), '0', STR_PAD_LEFT) : $str);
}
/**
* Decode int from base62.
* If $strict == true only strings with 5 or 6 characters are considered valid.
* Change it to false if a $pad other than 5 or 6 was used to encode.
*/
function int_from_base62($str, $strict=true) {
$str = (string) $str;
$l = strlen($str);
if ($strict && $l != 6 && $l != 5 || !$strict && ($l < 1 || $l > 6)) {
return null;
}
$powers = array(1, 62, 3844, 238328, 14776336, 916132832);
$n = 0;
for ($i = 0; $i < $l; ++$i) {
$v = strpos(BASE62_CHARS, $str[$l - $i - 1]);
if ($v === false) {
// invalid char
return null;
}
$n += $v * $powers[$i];
if ($n > BASE62_MAX || is_float($n)) {
// in PHP, int "overflows to float"
return null;
}
}
return $n;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.