PHP short connection generation

Source: Internet
Author: User
1 <? PHP 2 # Short join generation algorithm 3 4 class short_url {5 # tables Table 6 public static $ charset = "0123456789 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; 7 8 public static function short ($ URL) {9 $ key = "Alexis"; 10 $ urlhash = MD5 ($ key. $ URL); 11 $ Len = strlen ($ urlhash); 12 13 # divide the encrypted string into 4 segments, 4 bytes in each segment, and calculate each segment, A total of four short connections can be generated: 14 for ($ I = 0; $ I <4; $ I ++) {15 $ urlhash_piece = substr ($ urlhash, $ I * $ Len/4, $ Len/4); 16 # Compare the bit of a segment with 0 X3fffffff implements bitwise AND. 0x3fffffff indicates 30 1 of the binary number, that is, the encrypted strings after 30 bits are all set to 17 $ hex = hexdec ($ urlhash_piece) & 0x3fffffff; # Here you need to use hexdec () to convert the hexadecimal string to a 10-digit numeric type, otherwise the operation will not be normal 18 19 $ short_url = "http://t.cn /"; 20 # generate 6-bit transient connections 21 for ($ J = 0; $ j <6; $ J ++) {22 # convert the obtained value to 0x0000003d and the 3D value to 61, that is, the maximum coordinate value of charset is 23 $ short_url. = self: $ charset [$ hex & 0x0000003d]; 24 # After the loop is completed, move the hex right to 5 digits 25 $ hex = $ hex> 5; 26} 27 28 $ short_url_list [] = $ short_url; 29} 30 31 return $ Short_url_list; 32} 33} 34 35 $ url = "http://www.cnblogs.com/zemliu/"; 36 $ short = short_url: Short ($ URL); 37 print_r ($ short); 38?>

Array ([0] => http://t.cn/KyfLyH [1] => http://t.cn/bPafHS [2] => http://t.cn/H880aD [3] => http://t.cn/TmvDK0)

The generated short URL is saved to the server for a ing. short_url => original_url. When the short URL is entered, convert it back to the Long URL Based on the ing, and then access the original URL.

 

PS: Another idea is to store the URL in order. The first one is aaaaaa, the second is aaaaab... and so on. Do not use Hash, so it won't be repeated .. --

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.