PHP实现短网址功能,附代码

使用PHP实现短网址功能,支持短网址生成及跳转功能,暂不支持短网址解析,可以自定义开发反解析功能。实现原理是依据26个小写字母+26个大写字母+0-9数字,组成随机字符串。共计支持500多亿的组合模式,段时间内够用户使用。


PHP实现短网址功能,附代码

PHP


支持短链接生成、写入数据库,在访问时查询数据库,最终实现跳转功能。数据表设置为索引。

下面附代码:

<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/12/17 0017
* Time: 9:48
*/

namespace app\index\controller;

use think\Controller;

class Duan extends Controller
{
/**
* 生成
* @return mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function index()
{
$host = 'http://aabb.cn/';
$url = 'https://blog.gitee.com/';
//检测链接是否存在,存在则直接返回
$res = $this->check($url, 1);
if($res) {
echo '生成成功,链接:' . $host . $res;
die;
}
//不存在,生成,写入并返回
$code = $this->createStr();
//检测
$res = $this->check($code, 0);
if($res) {
$code = $this->createStr();
}
$result = db("sort")->insert(
[
'create_time' => time(),
'update_time' => time(),
'url' => $url,
'code' => $code,
]
);
if($result) {
echo '生成成功,链接:' . $host . $code;
die;
} else {
echo '生成失败';
die;
}
}

/**
* 检测资源是否存在
* @param $data
* @param $type
* @return array|false|\PDOStatement|string|\think\Model
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function check($data, $type)
{
if($type) {
$where['url'] = $data;
} else {
$where['code'] = $data;
}
$res = db("sort")->where($where)->find();
if($res and ($type == 1)) {
return $res['code'];
}
if($res and ($type == 0)) {
return $this->createStr();
}
}

/**
* 生成字符串
* @return string
*/
public function createStr()
{
$data = [
'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y',
'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2',
'3', '4', '5', '6', '7',
'8', '9' ];
$info = array_rand($data, 6);
$res = '';
foreach($info as $k => $v) {
$res .= $data[$v];
}
return $res;
}

/**
* 访问链接
* @param $code
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function info($code)
{
if(!$code) {
echo "无法访问";
die;
}
$data = db("sort")->where([ 'code' => $code ])->field('url')->find();
if(!$data) {
echo '无法获取连接';
die;
}
$this->redirect($data['url'], 301);
}
}

您可能还会对下面的文章感兴趣: