之前面试的时候,有面试官和我说md5做不了短链接,我也不知道他是怎么做,我感觉这样的做法应该没问题啊!
<?php
$or_url = $_GET['or_url'];
$md5_url = md5($or_url);
$salt = '0826';//这里不高于aaaa就不会出现61以上的数字,所以来说,后面的特别符号是不会出现的!
$md5_url = addSalt($md5_url,$salt);
$short_url = '';
for($i=0;$i<6;$i++){
$current_str = substr($md5_url,$i*6,6);
//处理当前串的值
$short_url .= ZChar($current_str);
}
echo $short_url;
function addSalt($md5_url,$salt){
if(strlen($md5_url) != 32){
die('addSalt:{$md5_url} error');
}
$len = strlen($salt);
for($i=0;$i<$len;$i++){
$position = hexdec($md5_url[$i]);
$weight = ceil($position/8);
$position = $position * $weight;
$pre = substr($md5_url,0,$position);
$next = substr($md5_url,$position);
$md5_url = $pre.$salt[$i].$next;
}
return $md5_url;
}
function dealStr($str){
if(strlen($str) != 6){
die("dealStr:{$str}error");
}
$count = '';
for($i=0;$i<6;$i++){
//加权,避免不同序列的和一致
$number = hexdec($str[$i])*($i+1)%12;
$count += $number;
}
return $count % 66;
}
function ZChar($current_str){
$Vchar = dealStr($current_str);
return char($Vchar);
}
function char($char_point){
$char_array = ["0","1","2","3","4","5",
"6","7","8","9","a","b","c","d",
"e","f","g","h","i","j","k","l",
"m","n","o","p","q","r","s","t",
"u","v","w","x","y","z","A","B",
"C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R",
"S","T","U","V","W","X","Y","Z",
"$","@",'+',"="];
$char_point = intval($char_point);
if($char_point < 0 || $char_point > 65){
die('char:'.$char_point.' error');
}
return $char_array[$char_point];
}
?>