大致分为两部分。短链接解码的实现思路:将传入的长链接存入数据库,记录创建时间,返回自增ID。将返回的id转16进制转16进制编码:例如自增id为10时,64位转换为A;即使我们记录一亿条记录,一亿个十六进制十六进制是:F9eEA,只有5个字符长,非常适合作为短链接的参数。然后组合成域名/编码参数/。我们都有短链接。当我们访问短链接时,解析参数转换为十进制。到数据库中找到对应的链接,进行301跳转。这个功能都是完整的。
粘贴以下代码:
1、修改host文件->配置网站虚拟目录->进行URL重写
为本机指定主机配置域名短链接解码,配置apache,启用虚拟目录配置。比如指定一个目录(不了解虚拟目录的同学可以百度一下)短链接解码,配置.htaccess文件核心方法:Url短连接实现原理及方法,进行如下设置:
2、增加十六进制编解码方式:
function b64dec($b64) { //十六进制转十进制
$map = 数组(
'0'=>0,'1'=>1,'2'=>2,'3'=>3,'4'=>4,'5'=>5,'6'=> 6,'7'=>7,'8'=>8,'9'=>9,
'A'=>10,'B'=>11,'C'=>12,'D'=>13,'E'=>14,'F'=>15,'G'=> 16,'H'=>17,'I'=>18,'J'=>19,
'K'=>20,'L'=>21,'M'=>22,'N'=>23,'O'=>24,'P'=>25,'Q'=> 26,'R'=>27,'S'=>28,'T'=>29,
'U'=>30,'V'=>31,'W'=>32,'X'=>33,'Y'=>34,'Z'=>35,'a'=> 36,'b'=>37,'c'=>38,'d'=>39,
'e'=>40,'f'=>41,'g'=>42,'h'=>43,'i'=>44,'j'=>45,'k'=> 46,'l'=>47,'m'=>48,'n'=>49,
'o'=>50,'p'=>51,'q'=>52,'r'=>53,'s'=>54,'t'=>55,'u'=> 56,'v'=>57,'w'=>58,'x'=>59,
'y'=>60,'z'=>61,'_'=>62,'='=>63
);
$dec = 0;
$len = strlen($b64);
for ($i = 0; $i < $len; $i++) {
$b = $map[$b64{$i}];
如果($b === NULL){
返回错误;
}
$j = $len - $i - 1;
$dec += ($j == 0 ? $b : (2 '0',1=>'1',2=>'2',3=>'3',4=>'4' ,5=>'5',6=>'6',7=>'7',8=>'8',9=>'9',
10=>'A',11=>'B',12=>'C',13=>'D',14=>'E',15=>'F',16=>'G ',17=>'H',18=>'I',19=>'J',
20=>'K',21=>'L',22=>'M',23=>'N',24=>'O',25=>'P',26=>'Q ',27=>'R',28=>'S',29=>'T',
短链接解码
30=>'U',31=>'V',32=>'W',33=>'X',34=>'Y',35=>'Z',36=>'a ',37=>'b',38=>'c',39=>'d',
40=>'e',41=>'f',42=>'g',43=>'h',44=>'i',45=>'j',46=>'k ',47=>'l',48=>'m',49=>'n',
50=>'o',51=>'p',52=>'q',53=>'r',54=>'s',55=>'t',56=>'u ',57=>'v',58=>'w',59=>'x',
60=>'y',61=>'z',62=>'_',63=>'=',
);
$b64 = '';
做{
$b64 = $map[($dec % 64)] . $b64;
$dec /= 64;
} 而 ($dec >= 1);
返回 $b64;
}
3、创建数据库链接完成短链接解码
4、创建短链接生成和长链接获取函数
define("HOST","localhost");
define("DB_NAME","db");
define("USER","root");
define("PASS","");
函数 make_short_url($url){
$url=str_ireplace("http://","",$url);
$pdo = new PDO("mysql:host=".HOST.";dbname=".DB_NAME,USER,PASS);
$rs = $pdo ->query("select id from links where url='".$url."'");
$row = $rs -> fetch();
如果($row==false){
$pdo -> exec("插入链接(url,ctime) 值('".$url."','".mktime()."')");
$id=$pdo -> lastinsertid();