我正在构建一个简单的 URL 缩短脚本,我想对 URL 进行哈希处理以用作唯一 ID,但如果我使用 MD5 之类的东西,则 URL 不会很短。
他们是一些散列函数还是创建一个只有 4 位或 5 位数字长的唯一 ID?
我正在构建一个简单的 URL 缩短脚本,我想对 URL 进行哈希处理以用作唯一 ID,但如果我使用 MD5 之类的东西,则 URL 不会很短。
他们是一些散列函数还是创建一个只有 4 位或 5 位数字长的唯一 ID?
散列会导致冲突。只需使用自动递增值。这也包括使用字母数字字符来压缩它。这就是大多数 URL 缩短器的工作方式。
尼克拉斯在下面的回答做得非常好。
使用自动递增整数并将它们转换为由所有字母(小写和大写)组成的标识符以缩短它们:
function ShortURL($integer, $chr='abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
// the $chr has all the characters you want to use in the url's;
$base = strlen($chr);
// number of characters = base
$string = '';
do {
// start looping through the integer and getting the remainders using the base
$remainder = $integer % $base;
// replace that remainder with the corresponding the $chr using the index
$string .= $chr[$remainder];
// reduce the integer with the remainder and divide the sum with the base
$integer = ($integer - $remainder) / $base;
} while($integer > 0);
// continue doing that until integer reaches 0;
return $string;
}
以及使它们恢复为整数的相应函数:
function LongURL($string, $chr='abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
// this is just reversing everything that was done in the other function, one important thing to note is to use the same $chr as you did in the ShortURL
$array = array_flip(str_split($chr));
$base = strlen($chr);
$integer = 0;
$length = strlen($string);
for($c = 0; $c < $length; ++$c) {
$integer += $array[$string[$c]] * pow($base, $length - $c - 1);
}
return $integer;
}
使用 MD5(或等效方法)的优点是可能性的数量如此之大,以至于您可以出于所有实际目的假设该值是唯一的。为确保 4 位随机类 ID 是唯一的,需要一个数据库来跟踪现有 ID。
本质上,您必须重复生成 ID 并检查数据库。
您始终可以只保留 MD5 的前 5 个字符,如果它已经存在,则向 url 字符串添加一个随机值并重试,直到获得唯一的。
我只是复制代码并运行它,看来他的字符串函数是倒退的。我输入了 shorturl 中生成的号码,然后回想了一下,得到了一个不同的号码。所以我解码了这个数字,发现字符串必须与上面的当前编码反向反馈到长 url。