扫描二维码 上传二维码
选择防红平台类型,避免链接被拦截
选择允许访问的平台类型

PHP实现短链接生成与解析:代码详解与最佳实践

"Fast Shorten URLs" Project Overview

The benefits of short links are manifold: they require content, are user-friendly, and are easy to manage. Implementing this project involves three key steps:

1. Defining a URL mapping algorithm that converts long URLs into shorter strings.
2. Utilizing storage solutions like databases or NoSQL for storing completed mappings.
3. Developing an efficient URL mapping algorithm.

The third step is the most challenging, as it involves devising a method to transform lengthy URLs into concise strings. Here are three approaches:

Common Implementation:
Drawing from your knowledge of base conversions between decimal, binary, and hexadecimal systems, we can employ a 62-character hexadecimal system to encode numeric IDs into short strings. This approach, while effective, does not guarantee uniform link lengths.



Link Analysis:
In summary, PHP-based link analysis and algorithm collection involve addressing the challenge of rapid distribution in high-concurrency scenarios. The specific implementation methods include:

/<em></em>
* Encodes a numeric ID into a shortened URL using hexadecimal characters.
* Note: This method does not ensure fixed-length links.
*
* @param int $integer The integer to be encoded.
* @param string $base The character set used for encoding.
*/
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;
}

/<em></em>
* Decodes a shortened URL back to its original numeric ID using hexadecimal characters.
*
* @param string $string The shortened URL.
* @param string $base The character set used for decoding.
*/
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;
}




Algorithm Explanation:
We use six characters to represent short links, selecting characters from the ASCII set: 'a'-'z', '0'-'9', and special characters. This results in a total of 32 characters per group, each capable of representing 32 states. Six characters can collectively represent 32^6 (1,073,741,824), ensuring unique identifiers. To generate these characters, we take the MD5 hash of the long URL, yielding a 32-bit string with minimal collision risk. We then divide this string into four parts, each consisting of eight characters, reducing the probability of collisions significantly. Each eight-character segment is treated as a hexadecimal number, and we extract the first five digits to map them onto our predefined 32-character set, resulting in a six-character short link.

PHP Short Link Implementation:
function shorten($long_url) {
$base32 = "abcdefghijklmnopqrstuvwxyz012345";
$hex = md5($long_url);
$hexLen = strlen($hex);
$subHexLen = $hexLen / 8;
$output = [];
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 & $subHex;
$out .= $base32[$val];
$subHex >>= 5;
}
$output[] = $out;
}
return $output;
}




Random Short Link Generation:
Below is a function that generates random short links using pure randomness. While querying operations can prevent reuse, this method's reliability remains questionable.



function random($length, $pool = '') {
if (empty($pool)) {
$pool = 'abcdefghkmnpqrstuvwxyz';
$pool .= '23456789';
}
srand((double)microtime() * 1000000);
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= substr($pool, rand(0, strlen($pool)), 1);
}
return $random;
}


Technical Tags: Short Links, Short URLs, Mapping, Hashing

This concludes the discussion on "PHP Short Link Algorithm, Source Code Sharing." For those interested, feel free to explore