php如何实现一个短网址服务,PHP实现短网址功能,附代码

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

PHP

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

下面附代码:/**

* Created by PhpStorm.

* User: Administrator

* Date: 2019/12/17 0017

* Time: 9:48

*/

namespace appindexcontroller;

use thinkController;

class Duan extends Controller

{

/**

* 生成

* @return mixed

* @throws thinkdbexceptionDataNotFoundException

* @throws thinkdbexceptionModelNotFoundException

* @throws thinkexceptionDbException

*/

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|thinkModel

* @throws thinkdbexceptionDataNotFoundException

* @throws thinkdbexceptionModelNotFoundException

* @throws thinkexceptionDbException

*/

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 thinkdbexceptionDataNotFoundException

* @throws thinkdbexceptionModelNotFoundException

* @throws thinkexceptionDbException

*/

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);

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值