PHP: Short id like Youtube, with salt

2019-03-16 21:59发布

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:

  1. Remove the $base parameter; that can be figured out by strlen ($chars)
  2. 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.?

2条回答
叛逆
2楼-- · 2019-03-16 22:18

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-03-16 22:37

Could you not just use PHP's uniqid function to generate a faux-random string from the current timestamp? Then save this alpha-numeric string in the video record at upload time.

查看更多
登录 后发表回答