This article mainly introduces three code examples for PHP to generate short URLs: pure random generation, enumeration generation, and 62-bit generation, you can refer to the short website service for friends who need it. many friends may not be familiar with it anymore. now, there are many application modes in most Weibo, mobile phone email reminders, and other places, and occupied a certain market. It is estimated that many of our friends are using the service now. I have read Sina's short connection service and found that there are 6 strings at the end.
There are too many algorithms and there is no need to discuss them too much. The most important thing is implementation. below are three methods of code:
<? Php // function random ($ length, $ pool = '') {$ random =''; if (empty ($ pool )) {$ pool = 'abcdefghkmnpqrstuvwxy'; $ pool. = '20140901';} srand (double) microtime () * 23456789); for ($ I = 0; $ I <$ length; $ I ++) {$ random. = substr ($ pool, (rand () % (strlen ($ pool), 1);} return $ random;} $ a = random (6 ); print_r ($ a); // function compute URL ($ input) of the enumeration generation method {$ base32 = 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 "); $ hex = md5 ($ input); $ hexLen = strlen ($ hex); $ subHexLen = $ hexLen/8; $ output = array (); for ($ I = 0; $ I <$ subHexLen; $ I ++) {$ subHex = substr ($ hex, $ I * 8, 8 ); $ int = 0x3FFFFFFF & (1 * ('0x '. $ subHex); $ out = ''; for ($ j = 0; $ j <6; $ j ++) {$ val = 0x0000001F & $ int; $ out. = $ base32 [$ val]; $ int = $ int> 5;} $ output [] = $ out;} return $ output;} $ a = response url (" http://www.bitsCN.com "); Print_r ($ a); // 62-bit generation method function base62 ($ x) {$ show =''; while ($ x> 0) {$ s = $ x % 62; if ($ s> 35) {$ s = chr ($ s + 61 );} elseif ($ s> 9 & $ s <= 35) {$ s = chr ($ s + 55);} $ show. = $ s; $ x = floor ($ x/62);} return $ show;} function urlShort ($ url) {$ url = crc32 ($ url ); $ result = sprintf ("% u", $ url); return base62 ($ result);} echo urlShort (" http://www.bitsCN.com /");?>