短链接服务的接实现 基于nginx url php redis 、js二维码生成 、js二维码识别

  1. 很容易想明白短链接是怎么实现的,无非就是把很长的URL存到服务器上,和一个短的url做一个映射。要做一个短链接,有一个很短的域名当然是再好不过了,信浪微博的短域名t.cn就短到了极致,自己申请短域名的话,两三位的包含数字和’-‘的短域名还挺多,.io/.me/.cn都是比较短的结尾名如a-.me在我写这篇博客时还没被注册。
  2. 短域名服务器端需要做的是快速重定向,所以不涉及安全,也不需要用https协议,够快就好。
  3. 我用nginx+php+redis来实现短链接。
  4. 得到的短链接形式如: a-.me/Af-2
  5. 注册短链接请求形式如:a-.me/admin.php?url=www.baidu.com
    下面是具体实现:

  1. 假设你已经安装好nginx + php + redis,网上资料很多,不再赘述
  2. nginx的配置:
location / {
      if (!-e $request_filename) {
          rewrite ^(.*)$ /index.php?s=$1 last;
      }
}

目的是为了让短链接省去index.php?s=
当然,我的/index.php指向了公司主页jdlxls.cn,所以用一个/s/路径来放,对应的nginx配置写法如下:

 location /s/ {
       if (!-e $request_filename) {
            rewrite ^/s/(.*)$ /s/index.php?s=$1 last;
       }
 }

相应的短域名形式为:jdlxls.cn/s/AgHf
3. 转发短链接程序 :index.php

<?php
$redis = new Redis();
$redis->connect('localhost',6379);
$short = $_GET['s'];
$long = $redis->hGet('s',$short);
if(!empty($long)){
        header("location: ".$long);
}else{
        header("location: http://jdlxls.cn);
}

4.短链接创建程序: admin.php

<?php
session_start();
define('PRE_URL','jdlxls.cn/s/');
define('ISPOST',$_SERVER['REQUEST_METHOD']=="POST");
if(isset($_SESSION['admin-user'])){//管理员已经登陆
      if(isset($_GET['exit'])){//退出登陆
         unset($_SESSION['admin-user']);
          echo '<script>location.href="https://jdlxls.cn/s/admin.php"</script>';exit;
       }elseif(isset($_GET['del'])){//删除记录
          $redis = getredis();
          $status = $redis->hDel('s',$_GET['del']);
          if($status){
              echo 'success';
              echo '<script >location.href="https://jdlxls.cn/s/admin.php" </script>';
          }
          exit;
       }
//管理员界面,列举出所有短链接,并可以做删除操作
       header('Content-Type: text/html; charset=utf-8');
       $redis = getredis();
       $all = $redis->hGetAll('s');
       echo '
<!doctype html>
<html>
<head>
</head>
<body>
<a href="https://jdlxls.cn/s/admin.php?exit">退出登陆</a>
<table border="1"><caption>映射列表</caption>
<thead><th>序号</th><th>短URL</th><th>长URL</th><th>删除</th></thead></tbody>
';
$count=0;
foreach($all as $key=>$value){
  $count++;
  echo"<tr><td>$count</td><td>jdlxls.cn/s/$key</td><td>$value</td><td><a href=\"https:/
/jdlxls.cn/s/admin.php?del=$key\">删除</a></td></tr>";
}
echo '
</tbody></table>
</body>
</html>
';
}elseif(ISPOST){// && isset($_POST['uname']) && isset($_POST['upwd']))){//管理员登陆
        if($_POST['uname'] && $_POST['upwd'] && $_POST['uname']=='admin' && $_POST['upw
d']=='123456'){
            $_SESSION['admin-user']='root';
            echo '<script>location.href="https://jdlxls.cn/s/admin.php"</script>';exit;

        }else{
            echo '<script>alert("登陆失败")</script>';
            echo '<script>location.href="https://jdlxls.cn/s/admin.php"</script>';
        }
}elseif(isset($_GET['url'])){//大众用户
        #$redis = new Redis();
        #$redis->connect(REDIS_HOST,REDIS_PORT);
        #$redis->auth(AUTH);
        #$redis->select(0);
        $redis=getredis();
        $key='';
        do{
            $key = shorten();
        }while($redis->exists($key));
        $status = $redis->hSet('s',$key,$_GET['url']);
        if($status)
           echo PRE_URL.$key;
        exit;
 }else{
        echo '
<!doctype html><html><head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>免费短链接服务</title>
  <style type="text/css"/>
    center {
      font:18px arial,sans-serif;
   }
   center label {
     background-color:#ccc;
   }
   center input[type="text"] {
     width:300px;i
     height:20px;
   }
   center input[type="submit"] {
      height:26px;
   }
  </style>
</head>
<body>
  <center>
  <form method="POST" action="admin.php"><label for="uname">用户名:</label> <input type="
text"  value="admin" name="uname"/>
<label for="pwd">密码:</label><input type="password" name="upwd"/><input type="submit"
value="登陆管理员"/></form><hr/>
  <form action="admin.php" method="get">
  <label for="url">长链接:(完整,http://或者https://开头)</label>
  <input type="text" required  name="url" placehold="https://...或者http://..." />
  <input type="submit" value="提交获得短链接"/>
  </center>
</body>
<script type="text/javascript">

</script>
</html>
';

}

function shorten($length=4,$pool='abcdefghkmnpqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM01234
56789-_*'){
    $random = '';
    srand ((double)microtime()*1000000);
    for($i = 0; $i < $length; $i++){
        $random .= substr($pool,(rand()%(strlen ($pool))), 1);}
    return $random;
}
function getredis(){
   $redis = new Redis();
   $redis->connect('localhost',6379);
   return $redis;
}

5.当中比较核心的算法就这一段:

function shorten($length=4,$pool='abcdefghkmnpqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM01234
56789-_*'){
    $random = '';
    srand ((double)microtime()*1000000);
    for($i = 0; $i < $length; $i++){
        $random .= substr($pool,(rand()%(strlen ($pool))), 1);}
    return $random;
}

写的比较low,网上有基于hash算法的实现,就不需要判断缓存里是否用过了某个短链接。


可以看看我的实现效果
js实现的二维码生成和识别的例子
这里写图片描述

这里写图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值