PHP implementation URL Long connection to short connection method summary

Source: Internet
Author: User
Tags repetition nginx server

Short link, in layman's terms, is to convert long URL urls into short URL strings through program calculations.

In this case, the advantages are: 1, content needs, 2, user-friendly, 3, easy to manage.

To implement short URL system more popular algorithms have two kinds of self-increment sequence algorithm, abstract algorithm

self-increment sequence algorithm:

The self-increment sequence algorithm is also called never repetition algorithm

Set ID self-increment, a 10 binary ID corresponds to a 62 binary value, 1 to 1, there will be no duplication of cases. This is used to reduce the number of characters when low-binary is converted to high-input.

Abstract algorithm:

1, the long URL md5 generated 32-bit signature string, divided into 4 segments, 8 bytes per segment

2, to the four-segment loop 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 ignore processing

3. The 30 bits are divided into 6 segments, and each 5-digit number takes a specific character as an index of the alphabet, and sequentially obtains a 6-bit string

4, the total md5 string can get 4 6-bit string, take any one inside can be used as this long URL short URL address

This algorithm, although generates 4 code, but there is still a chance of repetition

The above two kinds of algorithms specific implementation principle reference: short URL system principle and implementation

Based on the second algorithm, the URL long connection to short connection is implemented as follows:

Language: PHP5.6

Server environment: LNMP

Assumption: Long connection address: http://www.test.com/index.php

Short connection address: http://t.test.com/Six-bit code code

The first step: Using the Shorturl () function, generate a short connection code, and the data into the MySQL database;

function Shorturl ():

<?PHP/** * The short link operation is generated by a long connection * algorithm Description: Use 6 characters to denote a short link, we use the ASCII character of ' a '-' z ', ' 0 '-' 9 ', ' a '-' Z ', a total of 62 characters as a set. * Each character has 62 states, six characters can represent 62^6 (56800235584), then how to get these six characters, * specifically described as follows: * 1. Set the key value of the passed long url+ to Md5, get a 32-bit string (32 character hexadecimal number), that is 16 32 times; * 2. Divide the 32 bits into four parts, each 8 characters, as 16 binary strings and 0X3FFFFFFF (30 bit 1) and operation, i.e., more than 30 bits of ignoring processing; * 3.  The 30 bits are divided into 6 segments, each of the 5 groups, the integer value is calculated, and then mapped to the 62 characters we prepared, sequentially to get a 6-bit short link address. *   */  functionShorturl ($long _url )  {      $key= ' swz0823 ';//Custom Key value    $base= "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //using MD5 algorithm to generate hash value    $hex= Hash (' MD5 ',$long _url.$key); $hexLen=strlen($hex); $subHexLen=$hexLen/8; $output=Array();  for($i= 0;$i<$subHexLen;$i++ )      {          //divide the 32 bits into four parts, each 8 characters, as 16 binary strings and 0X3FFFFFFF (30 bit 1) and Operation        $subHex=substr($hex,$i*8, 8); $idx= 0X3FFFFFFF & (1 * (' 0x ').$subHex)); //The 30 bits are divided into 6 segments, each of the 5 groups, the integer values are calculated, and then mapped to the 62 characters we prepared.        $out= ' ';  for($j= 0;$j< 6;$j++ )          {              $val= 0x0000003d &$idx; $out.=$base[$val]; $idx=$idx>> 5; }          $output[$i] =$out; }            return $output; }      $url= ' http://www.test.com/index.php ';//Long Connections$ret= Shorturl ($url); Var_dump($ret); ################ Printing Results ################/*Array (4) {[0]=> string (6) "2aEzqe" [1]=> string (6) "Rj6bve" [2]=> string (6) "F2mqvi "[3]=> string (6)" Z2eqyv "}*/  #The long connection URL and the short link code result are stored in the database, with one for display. Example: Short connection address: http://t.test.com/2aezqe 

Database structure (customizable):

CREATE TABLE ' long_short_url ' (  ' id ' int (NULL auto_increment,  ' long_url ' varchar ( DEFAULT null,  ' short_url_code ' varchar (DEFAULTNULL,  ' Create_time ') varchar (DEFAULTNULL,  KEY  (' id ')) ENGINE  DEFAULT Charset=utf8;

The second step: Server 301/302 redirect API interface as follows, (fake so API interface address: HTTP://WWW.TEST.COM/API/LONGURL?) Code= six-bit code)

 Public function Longurl () {    $map$_get[' Code '];     $data =m (' Long_short_url ')->where ($map),find ();     $url $data [' Long_url '];     Header ("Location:$url");}

Fourth: Modify Nginx Server nginx.conf configuration file

Add the following code at the bottom (any position):

server_name T. Test.  ^/(. *) http://www.test.com/api/longurl?code=$1 redirect; access_log off;}

Then save and restart the Nginx server.

When we asked 短连接地址: to passthe http://t.test.com/2aezqe, 服务器会通过Code短码 2aEzqe 获取对应的长 URL,并通过HTTP 301/302重定向到对应的长连接地址;

Other than that:

1. Self-increment sequence algorithm implementation method reference example:PHP Implementation of short link system

2.PHP Open Source Short connection generation system:yourls

Yourls (Your Own URL shortener) is a short-link program developed using Php+mysql, allowing you to easily build your own short URL generation system. Without a third-party platform you can get all the stats and support a range of plug-in extensions.

Installation process:

    1. Unzip and upload the installation package to the server;
    2. will be renamed user/config-sample.php to user/config.php ;
    3. Edit user/config.php the file, fill in the database information and configure the site and other options;
    4. Access http://yoursite.com/admin/ !

PHP implementation URL Long connection to short connection method summary

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.