# apache 规则:RewriteRule ^DW(\w){4}$ /index\.php?md=xxx&cl=xxx&at=xxx [QSA] 规则自己写 再指定到地址
################################################## 1 ##################################################
/**
* 生成短连接
* 存数据库
*/
public function shortAction()
{
$LongLink = '/index.php?md=xxx&cl=xxx&at=xxx'; # 具体跳转的地址
$where = array("AND" => array("=" => array('long_link'=>$LongLink)));
$link = $this->model->getItemByOther($where,'short_link');
if($link){
echo $link[0]['short_link'];
}else{
$key_str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$key = substr(str_shuffle($key_str),mt_rand(0,strlen($key_str)-11),4);
$fields['short_link'] = $key;
$fields['long_link'] = $LongLink;
$fields['createdt'] = 'now()';
$status = $this->model->addItem($fields,'short_link');
echo $key;
}
}
/**
* apache 地址重写 接收url 解析长连接
*/
public function short2Action()
{
$REDIRECT_URL = substr($_SERVER['REDIRECT_URL'],1);
# $short_link = 'EQYd';
$where = array("AND" => array("=" => array('short_link'=>$REDIRECT_URL)));
$link = $this->model->getItemByOther($where,'short_link');
$host = 'http://www.xxx.com.cn'; # 域名
if($link){
$link = $host.$link[0]['long_link'];
header("Location: $link");exit;
}else{
echo "链接不存在";
}
}
附上数据字段:
create table short_link(
`id` int(11) not null auto_increment,
`short_link` varchar(60) not null comment '短链接',
`long_link` varchar(100) not null comment '长链接',
`createdt` datetime not null comment '',
primary key(id)
)engine=InnoDB default charset = utf8 row_format =dynamic ;
################################################## 2 ##################################################
或者还有一种直接简单的方式 只需要对apache设置,然后定义一个加密算法,访问后再解密,中间省去了操作数据库的存储,如果一定要存 考虑是否定期删除,如果必须要存数据库,且不删的情况下 还是建议存redis里