I need to encode/encrypt database ids and append them to my URLs. Security is not an issue I am trying to deal with, but I am looking for something with moderate security. The main goal is to have short ids that are unique and URL-safe.
The following snippet seems like it will do what I need (from http://programanddesign.com/php/base62-encode/)
function encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
// can't handle numbers larger than 2^31-1 = 2147483647
$str = '';
do {
$i = $val % $base;
$str = $chars[$i] . $str;
$val = ($val - $i) / $base;
} while($val > 0);
return $str;
}
function decode($str, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
$len = strlen($str);
$val = 0;
$arr = array_flip(str_split($chars));
for($i = 0; $i < $len; ++$i) {
$val += $arr[$str[$i]] * pow($base, $len-$i-1);
}
return $val;
}
echo encode(2147483647); // outputs 2lkCB1
I'll probably modify the functions a bit:
- Remove the $base parameter; that can be figured out by strlen ($chars)
- Eliminate from the character set letter/numbers that can be confused for each other (e.g. 0, O, o)
How would I change the script such I can also use a salt with it? And would that be a wise idea? Would I inadvertently increase chance of collision, etc.?