缩我短链接URL网址缩短的示例

2021-08-19 17:53:26

阅读 2779

短网址(Short URL)服务,在微博、微信推广、短信营销等营销活动中十分常见,比如,当我们在新浪微博发微博时有时发很长的网址连接,但微博限制字数140个字符,所以微博就自动把您发的长网址给转换成短网址了。为了更少的字数写更多的内容,压缩网址是非常重要的传播操作。

缩我短链接URL网址缩短的示例,详细步骤如下

1、post.html 页面

首先是post.html页面,用ajax请求返回短网址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
<html lang="en"
<head
    <meta charset="UTF-8"
    <title>Short URL DEMO from mimvp.comtitle
head
<script src="~~~">script
<script
    $(document).ready(function(){ 
        $("button").click(function(){ 
            var text = $("#text").val(); 
            $.ajax({ 
                url     : "shortUrl.php", 
                type    : 'post', 
                data    : {'text':text}, 
                success : function(data){ 
                  $("#url").val(data); 
                
            }) 
        }); 
    }) 
script
<body
   
    长网址: <input type="text" name="url" id="text" size="50"
   
    <button type="button" >提交button><br/> 
    短网址: <input type="text" id="url" val="" size="50"
   
body
html>

2、shortUrl.php 页面

把原网址和随机生成的8位码存入数据库,形成关联

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 接受post.html页面提交过来的数据 
$url = $_POST['text'];    // post.html提交过来的url 
   
# 生成随机8位码 
$txt = 'Z1X2C3V4B5N6M7A8S9D0FGHJKLQWERTYUIOP'
$code = ''
for ($i = 0; $i < 8; $i++) { 
    $code .= $txt[mt_rand(0, 35)]; 
   
# 把前端提交过来的原网址($url)和随机生成的8位码($str)一起存入数据库,目的为了到时候取的时候关联获取原网址 
$con = new mysqli('localhost','root','root','shorturl'); 
$sql = "insert into `short_url` (url,code) VALUES ('$url','$code')";//插入数据库 
$result = mysqli_query($con,$sql);

 

代码注释:

接下来拼接成短网址,然后返回前端页面

第一步:这是没有处理的网址如下(方便理解),后面进行伪静态和虚拟主机配置,就可以很简短

'localhost/shorturl/getUrl.php'这个是当输入短网址后,就可以到getUrl.php页面进行处理并重定向操作

echo 'http://localhost/shorturl/getUrl.php/'.$code;   // 这里是还没有处理的短网址,拼接$code目的是后面从浏览器地址获取进行数据库匹配

第二步:接下来就是如何把上面的短网址处理成自己想要的真正短网址

1.找到你的apache下面 conf/httpd.conf文件,把LoadModule rewrite_module modules/mod_rewrite.so 前面'#'去掉,表示启用重写功能,

并且也要去掉 Include conf/extra/httpd-vhosts.conf 前面 '#',表示启用虚拟主机配置

2、在你的文件根目录(也就是wamp/www/文件夹/)下,新建文件 .htaccess (注意文件名前面有 . )

1
2
3
4
5
6
7
8
 
Options +FollowSymlinks -Multiviews 
    RewriteEngine on 
   
    RewriteCond %{REQUEST_FILENAME} !-
    RewriteCond %{REQUEST_FILENAME} !-
    RewriteRule ^(.*)$ getUrl.php/$1 [QSA,PT,L] 
</IfModule>

 

RewriteRule ^(.*)$ getUrl.php/$1 [QSA,PT,L] 中 getUrl.php 表示要隐藏的文件名

第三步:在apache下的 conf/extra/httpd-vhosts.conf 加入

1
2
3
4
*:80
DocumentRoot "/var/html/www/shorturl/" 
    ServerName sgw.me 
</VirtualHost>

DocumentRoot 你的文件目录,ServerName 你的短网址(随意),配置好要重启apache才能生效

第四步:把你的 /etc/hosts  文件添加(要和你上面的ServerName保持一致,apache才能读取到)

127.0.0.1       suowo.cn

现在可以把上面“第一步”的 echo 'http://localhost/shorturl/getUrl.php/'.$code 换成

echo 'https://suowo.cn/'.$code;   // 这个就是真正短网址,例如:http://suowo.cn/WNL740SY 

 

3、getUrl.php 页面

当前端获取生成的短网址之后,这里获取短网址附带的8位随机码进行数据库查询原网址,然后重定向

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 获取短网址的后8位随机码 
$get_url = ''
if (isset($_SERVER['PATH_INFO'])) { 
    $get_url = $_SERVER['PATH_INFO']; 
}else if (isset($_SERVER['REDIRECT_PATH_INFO'])) { 
    $get_url = $_SERVER['REDIRECT_PATH_INFO']; 
}else if (isset($_SERVER['REDIRECT_URL'])) { 
    $get_url = $_SERVER['REDIRECT_URL']; 
#处理字符,因含有 '/' 
$get_url = ltrim($get_url,'/');//获得url地址栏额外参数 
   
#得到额外参数,进行判断 
if(isset($get_url) && !empty($get_url)){//针对 0 null '' 都是empty 
    $con = new mysqli('localhost','root','root','shorturl'); 
    $sql = "select url from 'short_url' where code='$get_url'"
    $result = mysqli_query($con,$sql); 
   
    #关联数组(重定向) 
    if($row=mysqli_fetch_assoc($result)) { 
        $real_url = $row['url']; 
        header('Location: ' . $real_url);//这里根据8位随机码对应取出原网址,就是重定向 
    }else
        header('HTTP/1.0 404 Not Found'); 
        echo 'Unknown link.'
    
   
}else
    header('HTTP/1.0 404 Not Found'); 
    echo 'Unknown link.'
}

 

 

短网址接口API

缩我短网址服务,用户可以通过访问缩我短链接首页输入原网址,生成对应的短网址,还可使用缩我短链接API开发的各种应用,调用缩我短网址服务。

此外,缩我短网址提供“还原网址”服务,用户看到一个已生成的短网址,想知道原来的网址是什么,可在“还原网址”页面输入短网址进行还原。

 

缩我生成短网址接口API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * [ShortURL_baidu 百度短网址接口]
 *
 * @param [integer] $type [非零整数代表长网址转短网址,0表示短网址转长网址]
 * @param [type] $url [要转的url]
 * @return [string] [返回转结果]
 * @author suowo.com
 */
function ShortURL_baidu($type, $url) {
    if ($type) {
        $baseurl = 'http://suowo.cn';
    } else {
        $baseurl = 'http://suowo.cn';
    }
     
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $baseurl );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    if ($type) {
        $data = array ( 'url' => $url );
    } else {
        $data = array ( 'tinyurl' => $url );
    }
     
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
    $strRes = curl_exec ( $ch );
    curl_close ( $ch );
    $arrResponse = json_decode ( $strRes, true );
    if ($arrResponse ['status'] != 0) {
        echo 'ErrorCode: [' . $arrResponse ['status'] . '] ErrorMsg: [' . iconv ( 'UTF-8', 'GBK', $arrResponse ['err_msg'] ) . "]";
        return 0;
    }
    if ($type) {
        return $arrResponse ['tinyurl'];
    } else {
        return $arrResponse ['longurl'];
    }
}
 
echo ShortURL_baidu ( 0, 'http://shuowo.cn/U9rzM8J' ); // 短网址转长网址
echo ShortURL_baidu ( 1, 'https://suowo.cn' );     // 长网址转短网址

 


缩我,高速云服务器
实时掌握推广动态
让您深入了解用户,提高推广转化率
联系我们
    1. 电话:400-001-9255
      联系客服
      常见问题
  • 公众号
    客服微信