PHP100 2019-03-27
代码如下:
/** * 利用62进制对数字ID进行短链接编码,缺点不能保证每个短链接是固定长度 * * @author wanshiqiang<[email protected]> * @param integer $integer * @param string $base */ private function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS) { $length = strlen($base); while($integer > $length - 1) { $out = $base[fmod($integer, $length)] . $out; $integer = floor( $integer / $length ); } return $base[$integer] . $out; } /** * 对62进制编码的短链接进行解码 * * @author wangshiqiang<[email protected]> * @param string $string * @param string $base */ private function getIDFromShortenedURL ($string, $base = ALLOWED_CHARS) { $length = strlen($base); $size = strlen($string) - 1; $string = str_split($string); $out = strpos($base, array_pop($string)); foreach($string as $i => $char) { $out += strpos($base, $char) * pow($length, $size - $i); } return $out; }
代码如下:
function shorten( $long_url ) { $base32 = "abcdefghijklmnopqrstuvwxyz012345"; $hex = md5( $long_url ); $hexLen = strlen( $hex ); $subHexLen = $hexLen / 8; $output = array(); for( $i = 0; $i < $subHexLen; $i++ ) { $subHex = substr( $hex, $i * 8, 8 ); $subHex = 0x3FFFFFFF & ( 1 * ('0x' . $subHex ) ); $out = ''; for( $j = 0; $j < 6; $j++ ) { $val = 0x0000001F & $int; $out .= $base32[$val]; $int = $int >> 5; } $output[] = $out; } return $output; }
代码如下:
function random($length, $pool = '') { $random = ''; if (empty($pool)) { $pool = 'abcdefghkmnpqrstuvwxyz'; $pool .= '23456789'; } srand ((double)microtime()*1000000); for($i = 0; $i < $length; $i++) { $random .= substr($pool,(rand()%(strlen ($pool))), 1); } return $random; }
参考资料:
4、Free PHP URL Shorten script that kicks ass
5、PHP Short Url Algorithm Implementation