本文實(shí)例講述了php生成短網(wǎng)址/短鏈接原理和用法。分享給大家供大家參考,具體如下:
需求
在我們的項(xiàng)目當(dāng)中,如果需要更好傳播我們的活動(dòng)鏈接,但是鏈接太長1來是不美觀,2來是太過于“笨重”,例如拼多多,淘寶聯(lián)盟,他們的推廣鏈接都是有短鏈接的,還有新浪微博。
但是,這些始終都是別人的,我們調(diào)用別人的API進(jìn)行生成,不穩(wěn)定,所以可以自己做一個(gè),注冊一個(gè)稍微短一些的域名就行。
相關(guān)學(xué)習(xí)推薦:php編程(視頻)
生成源碼api.php
<?php header("Content-type:application/json"); //GET URL $url = $_GET["url"]; //過濾數(shù)據(jù) if (trim(empty($url))) { echo "{"code":"1","url":"未傳入U(xiǎn)RL"}"; }else{ //定義數(shù)據(jù)庫配置 $dbhost = "xxx";//數(shù)據(jù)庫服務(wù)器地址 $dbuser = "xxx";//數(shù)據(jù)庫賬號(hào) $dbpwd = "xxx";//數(shù)據(jù)庫密碼 $dbname = "xxx";//數(shù)據(jù)庫名 //連接數(shù)據(jù)庫 $con = mysql_connect($dbhost,$dbuser,$dbpwd); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db($dbname, $con); //檢查數(shù)據(jù)庫是否已經(jīng)存在該URL $check = mysql_query("SELECT * FROM 表名 WHERE long_url = '$url'"); $check_result = mysql_num_rows($check); //如果已經(jīng)存在,則直接返回之前生成的鏈接 if ($check_result) { while ($row_yicunzai = mysql_fetch_array($check)) { $yicunzai_key = $row_yicunzai["dwz_key"]; //返回KEY echo "{"code":"0","url":"域名".$yicunzai_key.""}"; } }else{ //生成KEY $key_str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; $key = substr(str_shuffle($key_str),mt_rand(0,strlen($key_str)-11),4); //生成短鏈接 mysql_query("INSERT INTO lkydwz (long_url, dwz_key) VALUES ('$url', '$key')"); //返回結(jié)果 echo "{"code":"0","url":"域名".$key.""}"; } //斷開數(shù)據(jù)庫連接 mysql_close($con); } ?>
訪問源碼index.php
<?php header("Content-Type:text/html;charset=utf-8"); //獲得當(dāng)前傳過來的KEY $key = $_GET["id"]; echo "<title>正在跳轉(zhuǎn)</title>"; //過濾數(shù)據(jù) if (trim(empty($key))) { echo "鏈接不存在"; }else{ //解析KEY //定義數(shù)據(jù)庫配置 $dbhost = "xxx";//數(shù)據(jù)庫服務(wù)器地址 $dbuser = "xxx";//數(shù)據(jù)庫賬號(hào) $dbpwd = "xxx";//數(shù)據(jù)庫密碼 $dbname = "xxx";//數(shù)據(jù)庫名 //連接數(shù)據(jù)庫 $con = mysql_connect($dbhost,$dbuser,$dbpwd); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db($dbname, $con); //查詢數(shù)據(jù)庫,通過KEY獲取長鏈接進(jìn)行跳轉(zhuǎn) //檢查數(shù)據(jù)庫是否存在該KEY $check = mysql_query("SELECT * FROM 表名 WHERE dwz_key = '$key'"); $check_result = mysql_num_rows($check); //如果存在,則解析出長鏈接并跳轉(zhuǎn) if ($check_result) { while ($row_long_url = mysql_fetch_array($check)) { $long_url = $row_long_url["long_url"]; // echo "<script>location.href="".$long_url."";</script>"; header("Location: $long_url"); } }else{ echo "鏈接不存在"; } } ?>
Apache規(guī)則.htaccess
RewriteEngine On #RewriteBase / RewriteRule ^(w+)$ index.php?id=$1
數(shù)據(jù)庫字段
id(int)自增 dwz_key(varchar) long_url(text) creat_time(TIMESTAMP)
使用方法
1、訪問api.php?url=長鏈接,即可生成短鏈接,例如返回JSON
{"code":"0","url":"http://xxx.cn/Hp8R"}
2、新建.htaccess,把上面規(guī)則復(fù)制進(jìn)去,保存
3、新建index.php,把上面代碼拷貝進(jìn)去,配置好數(shù)據(jù)庫。訪問http://xxx.cn/Hp8R,就會(huì)自動(dòng)跳轉(zhuǎn)到你的長鏈接
相關(guān)學(xué)習(xí)推薦:編程視頻