WEB:建立短链接服务

来源:互联网 发布:sql select as 编辑:程序博客网 时间:2024/06/06 00:47

现有在线服务

在实现分享功能的时候特别需要短链接服务,已有的在线url shorten服务包括:

1. TinyUrl,API地址 http://tinyurl.com/api-create.php?url=your-url

2. Bitly(bit.ly, 不能访问...)

3. Yourls,API地址 http://yourls.org/#API

4. dwz,百度提供的服务,API地址:http://dwz.cn/create.php

5. u2l,在线服务,API地址:http://www.u2l.info/encode?url=your-url

6. Goo,Google提供的服务,API地址:http://goo.gl/

百度的dwz服务限制很多,可能有白名单限制,不受信任的域名不能工作

建立自己的服务

为了服务更稳定,性能更好,以及避免一些UI跨域调用的麻烦,可以建立自己的短链接服务:
1. 短链接生成,可以使用一些字符串hash函数,最简单的用md5来做,也可以随机生成一个固定长度的字母数字串
2. 把短链接和原始链接建立对应关系,可放在文件(量小的情况下)、内存数据库或MySQL中
3. 请求过来的时候,解析出短链接,根据2建立的对应关系查询到长链接,然后重定向
以下是基于PHP和MySQL的示范代码:

function getLongURL($s){$host = ""; $user = ""; $pass = ""; $db = "";$mysqli = new mysqli($host, $user, $pass, $db);if (mysqli_connect_errno()) { die("Unable to connect !"); }$query = "SELECT * FROM urls WHERE shorturl = '$s';";if ($result = $mysqli->query($query)) {    if ($result->num_rows > 0) {while($row = $result->fetch_assoc()) {return($row);}    } else {    return false;    }} else {return false;}$mysqli->close();}function redirectTo($longURL){header("Referer: http://www.your-domain-here.com");header("Location: $longURL", TRUE, 301);exit;}$expectedURL = trim($_SERVER['URL']);$split = preg_split("{:80\/}",$expectedURL);$shortURL = $split[1];// security: strip all but alphanumerics & dashes$shortURL = preg_replace("/[^a-z0-9-]+/i", "", $shortURL);$isShortURL = false;$result = getLongURL($shortURL);if ($result) { $isShortURL = true; }$longURL = $result['longURL'];if ($isShortURL){redirectTo($longURL, $shortURL);} else {//do as usual link}

by iefreer
0 0
原创粉丝点击