使用php實現短網址功能,支持短網址生成及跳轉功能,暫不支持短網址解析,可以自定義開發反解析功能。實現原理是依據26個小寫字母+26個大寫字母+0-9數字,組成隨機字符串。共計支持500多億的組合模式,段時間內夠用戶使用。
PHP
支持短鏈接生成、寫入數據庫,在訪問時查詢數據庫,最終實現跳轉功能。數據表設置為索引。
下面附代碼:
<?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); } }