PHP:短id像Youtube,用盐 [英] PHP: Short id like Youtube, with salt
问题描述
我需要对数据库ID进行编码/加密,并将其附加到我的网址。安全不是我想要处理的问题,但我正在寻找一些与中度安全。主要目标是具有唯一和URL安全的短ids。
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.
以下代码段似乎会做我需要的(从 http://programanddesign.com/php/base62-encode/ )
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:
- 删除$ base参数; ($ chars)
- 从可能彼此混淆的字符集字母/数字中删除(例如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.?
推荐答案
如果你想让字符串中的数字id无法猜测,可以使用盐。你应该能够让id回来没有冲突。 使用PHP创建简短ID(例如Youtube或TinyURL )的作者:Kevin van Zonneveld是一个好的开始。无论如何,请检查唯一性。
If you want to make the numerical id unguessable from the string, you can use a salt. You should be able to get the id back without collisions. The post Create short IDs with PHP - Like Youtube or TinyURL by Kevin van Zonneveld is a good start. At any rate, check for uniqueness.
这篇关于PHP:短id像Youtube,用盐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!