Home  >  Article  >  Backend Development  >  Ideas and implementation of generating short URLs in PHP

Ideas and implementation of generating short URLs in PHP

WBOY
WBOYOriginal
2016-07-25 08:54:421170browse
  1. RewriteEngine On
  2. RewriteBase /
  3. RewriteRule ^/(.*)$ link.php?url=$1[L]
Copy code

implemented http://t.cn/link. php?url=zHEYrvV is converted to http://t.cn/zHEYrvV, which is much shortened. So how to find the URL http://bbs.it-home.org/sitejs-17300-1.html through zHEYrvV? 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.

Combined with this example, we go to the database to find the corresponding URL according to the incoming parameter zHEYrvV. If we find it, we will jump to it with the header.

Share a PHP short URL generation code (here, the long URL is generated to a length of 5-6 characters and needs to be unique):

  1. function code62($x){
  2. $show='';
  3. while($x>0){
  4. $s=$x % 62;
  5. if ($s>35 ){
  6. $s=chr($s+61);
  7. }elseif($s>9&&$s<=35){
  8. $s=chr($s+55);
  9. }
  10. $show.=$s ;
  11. $x=floor($x/62);
  12. }
  13. return $show;
  14. }
  15. function shorturl($url){
  16. $url=crc32($url);
  17. $result=sprintf("%u" ,$url);
  18. return code62($result);
  19. }
Copy code

For example echo shorturl('http://bbs.it-home.org/'); A unique corresponding code will be generated.

For url rewriting methods, please refer to the article: php pseudo-static url rewriting simple example How to write php pseudo-static (url rewriting) How to quickly rewrite url in php5.3 or above version



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn