PHP short link, short URL, short URL implementation code

Source: Internet
Author: User
  1. /**
  2. * Short Connection generation algorithm
  3. * site:bbs.it-home.org
  4. */
  5. Class Short_url {
  6. #字符表
  7. public static $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
  8. public static function short ($url) {
  9. $key = "Alexis";
  10. $urlhash = MD5 ($key. $url);
  11. $len = strlen ($urlhash);
  12. #将加密后的串分成4段, 4 bytes per segment, calculated for each segment, can generate four short connections altogether
  13. for ($i = 0; $i < 4; $i + +) {
  14. $urlhash _piece = substr ($urlhash, $i * $len/4, $len/4);
  15. #将分段的位与0x3fffffff做位与, 0X3FFFFFFF represents a binary number of 30 1, that is, 30-bit after the encryption string is zeroed
  16. $hex = Hexdec ($urlhash _piece) & 0x3fffffff; #此处需要用到hexdec () Converts a 16 binary string to a 10-binary numeric type, otherwise the operation will be unhealthy
  17. $short _url = "http://t.cn/";
  18. #生成6位短连接
  19. for ($j = 0; $j < 6; $j + +) {
  20. #将得到的值与0x0000003d, 3d is 61, which is the coordinate maximum of charset
  21. $short _url. = self:: $charset [$hex & 0x0000003d];
  22. #循环完以后将hex右移5位
  23. $hex = $hex >> 5;
  24. }
  25. $short _url_list[] = $short _url;
  26. }
  27. return $short _url_list;
  28. }
  29. }
  30. $url = "http://www.bbs.it-home.org/jb//";
  31. $short = Short_url::short ($url);
  32. Print_r ($short);
  33. ?>
Copy Code

Output: 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 stored in the server, make a map, Short_url = Original_url, enter the short URL by mapping back to the long URL, and then access the original URL.

Code:

  1. Class TinyURL {
  2. static Private $key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; You can make sure that each character is displayed correctly in the URL.
  3. Private Function __construct () {}
  4. Private Function __clone () {}
  5. static public function encode ($value) {
  6. $base = strlen (self:: $key);
  7. $arr = Array ();
  8. while ($value! = 0) {
  9. $arr [] = $value% $base;
  10. $value = Floor ($value/$base);
  11. }
  12. $result = "";
  13. while (Isset ($arr [0])) $result. = substr (self:: $key, Array_pop ($arr), 1);
  14. return $result;
  15. }
  16. static public Function decode ($value) {
  17. $base = strlen (self:: $key);
  18. $num = 0;
  19. $key = Array_flip (Str_split (self:: $key));
  20. $arr = Str_split ($value);
  21. for ($len = count ($arr)-1, $i = 0; $i <= $len; $i + +) {
  22. $num + = Pow ($base, $i) * $key [$arr [$len-$i]];
  23. }
  24. return $num;
  25. }
  26. }
Copy Code

Invocation Example:

    1. $t = 100;
    2. $time _start = Microtime (true);
    3. while ($t-) {
    4. Var_dump (Tinyurl::encode (1000000));
    5. Var_dump (tinyurl::d ecode ("4c92"));
    6. }
    7. $time _end = Microtime (true);
    8. printf ("[Memory Use:%.2fmb]\r\n", Memory_get_usage ()/1024/1024);
    9. printf ("[Maximum Memory Use:%.2fmb]\r\n", Memory_get_peak_usage ()/1024/1024);
    10. printf ("[Execution time:%.2f Ms]\r\n", ($time _end-$time _start) * 1000);
Copy Code

The code above applies to: a traditional relational database with a self-increment ID. Need to execute two SQL, first obtained from the increment ID, the second time to generate a short link based on the ID. [or 3 times, an additional time to determine if this short link exists.] ]

In addition, there is a hash algorithm based on the URL, the advantages of this algorithm: 1, no need for ID, in the form of key/value to satisfy the storage. 2,sql Insert requires only one statement. 3, the generated data is discrete, unable to observe the rule of generation.

Cons: 1, so the hash algorithm has the possibility of conflict, once the conflict is original will be overwritten. [Of course you can add extra logic to judge.] ] 2, the data size is not control, you do not know when to start using the new hash data bits, but as the amount of data increases, the probability of conflict will be higher. This code applies to non-relational databases such as NoSQL, looking for fast updates.

  • 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.