The short URL is to convert a long address in the Super short URL, and then visit the short URL to jump to the long URL, the following is the implementation of the URL to the PHP algorithm and examples of short URLs.
Short URLs, as the name implies, are in the form of relatively short URLs. In Web 2.0 today, it has to be said that this is a trend. There are already many similar services, with short URLs you can use a short URL instead of the original lengthy URL, so that users can easily share links.
Algorithm principle
1) to generate a long URL MD5 32-bit signature string, divided into 4 segments, 8 bytes per segment;
2) for this four-segment cycle processing, take 8 bytes, he is regarded as 16 binary string and 0X3FFFFFFF (30 bit 1) and operation, that is, more than 30 bits of ignoring processing;
3) The 30 bits are divided into 6 segments, and each 5 digit number is taken as an index of the alphabet to obtain a specific character, followed by a 6-bit string;
4) The total MD5 string can obtain 4 6-bit strings; Take any one inside to be the short URL address for this long URL;
Here is the algorithm for short URL conversion using PHP, the code is as follows:
Php
The code is as follows |
Copy Code |
<?php Short URL generation algorithm Class Shorturl {
Character Tabulation public static $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static function encode ($url) { $key = ' abc '; Add salt $urlhash = MD5 ($key. $url); $len = strlen ($urlhash);
Divide the encrypted string into 4 segments, 4 bytes per segment, calculate each segment, and generate four short connections altogether for ($i = 0; $i < 4; $i + +) { $urlhash _piece = substr ($urlhash, $i * $len/4, $len/4);
The bits of the segment are made with 0X3FFFFFFF, and the 0X3FFFFFFF represents 30 1 of the binary number, that is, the 30-bit encryption string is zeroed You need to use HEXDEC () to convert the 16 binary string to a 10 binary numeric type, otherwise the operation will be abnormal $hex = Hexdec ($urlhash _piece) & 0x3fffffff;
Domain name fill in according to demand $short _url = "http://t.cn/"; Generate 6-bit short URLs for ($j = 0; $j < 6; $j + +) {
The resulting value is 0x0000003d,3d to 61, which is the maximum coordinate value of the CharSet $short _url. = self:: $charset [$hex & 0x0000003d];
Move Hex to the right 5 bits after the loop is finished $hex = $hex >> 5; }
$short _url_list[] = $short _url; }
return $short _url_list; } }
$url = "http://www.111cn.net/"; $short = Shorturl::encode ($url); Print_r ($short); ?> |
Usually we use the first group in the four-group URLs.
It is important to note that this algorithm is irreversible, therefore, the usual practice is to save the short URL and the corresponding original URL into the database, when accessed, from the database to remove the matching original URL, through 301 or header to jump.
Example of algorithm for URL translation of short URLs using PHP