The Thoughts of Generating Short Website by PHP and the Detailed Explanation of the Implementation Method

  • 2021-12-04 18:17:54
  • OfStack

Short URLs have been popular for a period of time, especially on Sina Weibo, but many people don't know how this thing is realized. In fact, short URLs are quite easy. Below, we describe the idea of generating short URLs and the implementation method of generating short URLs using php.

The idea of generating short URL: If the short URL is restored, do you know what it looks like? Maybe you can see that the short URLs in Sina Weibo app are all like this:

http://t.cn/RzddsXt

In fact, he restored it. Maybe this is what it looks like:

http://t.cn/link.php?url=//www.ofstack.com/

According to this format, you can know that this short website is actually processed through the page link. php, so how to

http://t.cn/link.php?url=//www.ofstack.com/

Shrink into

http://t.cn/RzddsXt

This place needs to be rewritten by url. According to this example, it can be rewritten as follows:


RewriteEngine On
RewriteBase /
RewriteRule ^/(.*)$ link.php?url=$1[L]

Here, http://t.cn/link.php? url=RzddsXt is converted to http://t.cn/RzddsXt, which is shortened a lot. So how can I find the website //www.ofstack.com/ through RzddsXt and jump to this website? Here used a similar encryption algorithm, through the algorithm to shorten all the long URLs into a corresponding 5-6 bits and only 1 string, and the corresponding relationship stored in the database. Combined with this example is to find the corresponding URL in the database according to the passed parameter RzddsXt, and jump to header when it is found.

ok, as for the idea of generating short URLs, this is what it looks like.

Let's share the process of generating short URLs through php under 1 (here, long URLs are generated as short as 5-6 characters in length and need to be only 1):


<?php
function code62($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 shorturl($url){
 $url=crc32($url);
 $result=sprintf("%u",$url);
 return code62($result);
}
?>

For example:


echo shorturl('//www.ofstack.com/');

Will generate a only 1 corresponding code for S54Aq, OK, as for how to do url rewrite and database storage here is not much written, according to their own situation.

PS: Here we recommend a short URL generation tool for this site (also a short URL generated by the third party API interface)

Short chain (short website) online generation tool:

http://tools.ofstack.com/password/dwzcreate

Summarize


Related articles: