php基于tp5.1 实现短链接功能 (redis+nginx)

  1. 生成及存储短链接
// 生成短链接
function get_rand_str($len = 12)
{
    if (!is_int($len) || $len < 0) {
        return false;
    }

    $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';
    for ($i = $len; $i > 0; $i--) {
        $string .= $char[mt_rand(0, strlen($char) - 1)];
    }

    return $string;
}


// 存储短链接对应的长链接
function set_cache($real_url, $expire = 3600)
{
    $key = get_rand_str(6);
    // cache 为redis实例, 此处以tp5.1为例, 其他框架需更改为自己的用法
    if (cache($key)) {
        return self::set_cache($real_url);
    } else {
        cache($key, $real_url, $expire);
    }

    return $key;
}

 

  2. 更改nginx配置, 将短链接重定向到处理文件

server{
  ....

    #短链接(http(s)://xxx.com/s/xxx)重定向到 s文件夹下的share.php处理文件
       location /s/ {
            rewrite ^(/s/)(.*)$ $1/share.php?k=$2;
    }      
}

 

share.php文件


<?php

/**
* @desc Class Share 分享处理类
* @author Ni
* @date 2020年10月19日10:26:41
*/
class Share
{
private static $instance;

private function __clone()
{
}

private $config = null;
private $redisConf = null;
private $redisHandle = null;
private $url = null;

//构造方法私有化,防止外部创建实例
private function __construct()
{
}

public static function getInstance()
{
//判断实例有无创建,没有的话创建实例并返回,有的话直接返回
if (!(self::$instance instanceof self)) {
self::$instance = new self();
}
return self::$instance;
}

private function init()
{
$this->getConfig();
$this->initRedisHandle();
}

/**
* @desc 获取配置
*/
private function getConfig()
{
// $this->config = include_once './config.php';
$this->config = [
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
// 全局缓存有效期(0为永久有效)
'expire' => 3600,
// 缓存前缀
'prefix' => '',
'password' => 'you_redis_password'
]
];

if (isset($this->config['redis'])) {
$this->redisConf = $this->config['redis'];
} else {
$this->return404();
}
}

private function return404()
{
$html = file_get_contents('./404.html');
echo $html;
exit;
}

private function initRedisHandle()
{
try {
if (!$this->redisHandle) {
$this->redisHandle = new Redis();
$this->redisHandle->connect($this->redisConf['host'], $this->redisConf['port'], $this->redisConf['expire']);
$this->redisHandle->auth($this->redisConf['password']);
} else {
return true;
}
} catch (Exception $e) {
$this->return404();
}

}

private function getUrl()
{
// 获取get参数k
$k = isset($_GET['k']) ? $_GET['k'] : '';
if (!$k) {
$this->return404();
}

// 获取缓存信息
$cache = $this->redisHandle->get($this->redisConf['prefix'] . $k);
if (!$cache) {
$this->return404();
}
$this->url = $cache;

}

private function redirectUrl()
{
if ($this->url) {
header("Location: $this->url");
} else {
$this->return404();
}
exit;
}

function run()
{
$this->init();
$this->getUrl();
$this->redirectUrl();
}
}

$share = Share::getInstance();
$share->run();
 

附录: 404.html(页面代码来源于网络)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta charset="UTF-8" http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>404-对不起!您访问的页面不存在</title>

    <style type="text/css">

        .head404{ width:580px; height:234px; margin:50px auto 0 auto; background:url(https://www.daixiaorui.com/Public/images/head404.png) no-repeat; }

        .txtbg404{ width:499px; height:169px; margin:10px auto 0 auto; background:url(https://www.daixiaorui.com/Public/images/txtbg404.png) no-repeat;}

        .txtbg404 .txtbox{ width:390px; position:relative; top:30px; left:60px;color:#eee; font-size:13px;}

        .txtbg404 .txtbox p {margin:5px 0; line-height:18px;}

        .txtbg404 .txtbox .paddingbox { padding-top:15px;}

        .txtbg404 .txtbox p a { color:#eee; text-decoration:none;}

        .txtbg404 .txtbox p a:hover { color:#FC9D1D; text-decoration:underline;}

    </style>

</head>



<body bgcolor="#494949">

<div class="head404"></div>

<div class="txtbg404">

    <div class="txtbox">

        <p>对不起,您请求的页面不存在、或已被删除、或暂时不可用</p>

        <p class="paddingbox">请点击以下链接继续浏览网页</p>
        <p><a href="你的网站首页">返回网站首页</a></p>

    </div>

</div>

</body>

</html>
</html>

 

posted @ 2020-11-05 11:39  also_think  阅读(569)  评论(0编辑  收藏  举报