Home > Database > Mysql Tutorial > How to use PHP and MySQl to generate and read short URLs

How to use PHP and MySQl to generate and read short URLs

WBOY
Release: 2023-05-27 10:52:38
forward
1183 people have browsed it

PHP+MySQl实现短网址的生成和读取

常规的方案我们将生成好的短网址和原网址对应到一张数据表中,然后供读取使用。我们先来看如何生成唯一的短网址。

//生成短网址 
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); 
} 
echo shorturl(&#39;https://www.jb51.net/&#39;); 
//1EeIv2
Copy after login

使用以上PHP代码可以生成唯一的6位的短网址,然后我们将生成的短网址与原网址一起写入到MySQL表中,插入数据库的代码这里我就不写了,这是PHP基础。
接着,我们有一个link.php用来接收读取url并实现真实跳转。

include_once(&#39;connect.php&#39;); //连接数据库 
$url = $_GET[&#39;url&#39;]; 
if(isset($url) && !empty($url)){ 
  $sql = "select url from shorturl where codeid=&#39;$url&#39;"; 
  $query = mysql_query($sql); 
  if($row=mysql_fetch_array($query)){ 
    $real_url = $row[&#39;url&#39;]; 
    header(&#39;Location: &#39; . $real_url); 
  }else{ 
    header(&#39;HTTP/1.0 404 Not Found&#39;); 
    echo &#39;Unknown link.&#39;; 
  } 
}else{ 
  header(&#39;HTTP/1.0 404 Not Found&#39;); 
  echo &#39;Unknown link.&#39;; 
}
Copy after login

代码中,如果得到短网址对应的真实url,会使用header跳转到真实的页面上去,否则返回404代码。这样我们可以使用如: http://yourdomain/link.php?url=xxx来实现短网址访问。

继续,我们使用URL rewrite即重写功能来实现诸如可以通过地址:http://yourdomain/xxx 来访问。

以下是rewrite规则:

#Apache规则: 
RewriteRule ^/(.*)$ /link.php?url=$1 [L] 
 
#如果使用nginx,规则这样写: 
rewrite ^/(.*)$ /link.php?url=$1 last;
Copy after login

The above is the detailed content of How to use PHP and MySQl to generate and read short URLs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template