PHP: Short id like Youtube, with salt

两盒软妹~` 提交于 2019-12-20 14:21:47

问题


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.?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4153628/php-short-id-like-youtube-with-salt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!