The idea of generating a short URL: If you restore the short URL, do you know what it will look like? For example:
http://www.jbxue.com/sitejs-17300-1.html
For the above link, in addition to opening it directly, there is another way to open it, as follows:
http: //www. jbxue.com/link.php?url=http://www.jbxue.com/sitejs-17300-1.html
Okay, the short URL is restored and it actually looks like this. Maybe you I saw that the short URLs in the Sina Weibo application all look like this:
http://t.cn/zHEYrvV
In fact, he restored it and it might look like this:
http://t.cn /link.php?url=http://www.jbxue.com/sitejs-17300-1.html
Okay, here comes the second step, how to use
http://t. cn/link.php?url=http://www.jbxue.com/sitejs-17300-1.html
Shrink to
http://t.cn/zHEYrvV
This place needs to be used URL rewriting, according to this example, can be rewritten as follows:
RewriteEngine On
RewriteBase /
RewriteRule ^/(.*)$ link.php?url=$1[L]
It is implemented here http://t.cn/link.php?url=zHEYrvV has been converted to http://t.cn/zHEYrvV, which has been shortened a lot. So how to find http://www.jbxue.com through zHEYrvV? /sitejs-17300-1.html and jump to this URL? An encryption-like algorithm is used here. Through the algorithm, all long URLs are shortened into a corresponding 5-6-digit and unique string, and this correspondence is stored in the database. Combining this example is to go to the database to find the corresponding URL based on the incoming parameter zHEYrvV. If found, the header will jump to it.
ok, as for the idea of generating a short URL, this is what it looks like.
The process of generating a short URL through php (here the long URL is generated as short as 5-6 characters in length and needs to be unique):
<?<span php </span><span function</span> code62(<span $x</span><span ){ </span><span $show</span>=''<span ; </span><span while</span>(<span $x</span>>0<span ){ </span><span $s</span>=<span $x</span> % 62<span ; </span><span if</span> (<span $s</span>>35<span ){ </span><span $s</span>=<span chr</span>(<span $s</span>+61<span ); }</span><span elseif</span>(<span $s</span>>9&&<span $s</span><=35<span ){ </span><span $s</span>=<span chr</span>(<span $s</span>+55<span ); } </span><span $show</span>.=<span $s</span><span ; </span><span $x</span>=<span floor</span>(<span $x</span>/62<span ); } </span><span return</span> <span $show</span><span ; } </span><span //</span><span www.jbxue.com</span> <span function</span> shorturl(<span $url</span><span ){ </span><span $url</span>=<span crc32</span>(<span $url</span><span ); </span><span $result</span>=<span sprintf</span>("%u",<span $url</span><span ); </span><span return</span> code62(<span $result</span><span ); } </span>
echo shorturl('http://www.jbxue.com/');
The unique corresponding code that will be generated is n2Q8e.
Reference article: