短网址的原理解析

widuu 2013-4-22 PHP技术 7,940 1 喜欢 (0)

有人问我短网址到底怎么做,自己能做吗?我说可以而且原理非常简单?下边是我的代码和配置分享出来,叫你2分钟急速编程做短网址
win8的iis8的 URL rewrite 支持iis7
[php]
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="url">
<match url="^(.*)a(.*)$" />
<action type="Rewrite" url="{R:1}/index.php?a={R:2}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
[/php]
iis6的
[php]
[ISAPI_Rewrite]
# 3600 = 1 hour
CacheClockRate 3600
RepeatLimit 32
# Protect httpd.ini and httpd.parse.errors files
# from accessing through HTTP
RewriteRule ^(.*)a(.*)$ $1/index\.php\?a$2
[/php]
apache的伪静态
[php]
# 将 RewriteEngine 模式打开
RewriteEngine On
# Rewrite 系统规则请勿修改
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^a(.*)$ index.php?a=$1
[/php]
程序代码
[php]
<?php
/*
*CREATE TABLE `url_demo` (
* `id` int(11) NOT NULL AUTO_INCREMENT,
* `durl` varchar(9) NOT NULL,
* `zurl` varchar(250) NOT NULL,
* PRIMARY KEY (`id`)
* ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*
*/
$conn = mysql_connect("localhost","root","");
mysql_select_db("test",$conn);
$u = $_GET[a];
$sql = "select zurl from url_demo where durl = '".$u."'";
$data = mysql_query($sql);
$result = mysql_fetch_array($data);
if($result['zurl']!==""){
header("Location:{$result['zurl']}");
}

//生成随机函数
function create_randomstr($lenth = 6) {
return random($lenth, '123456789bcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}

function random($length, $chars = '0123456789') {
$hash = '';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
$durl = create_randomstr(6);
$zurl = 'http://www.widuu.cn';

$sr = mysql_query("insert into url_demo (durl,zurl) value ('{$durl}','{$zurl}')");
if($sr){
echo "您的短网址是http://localhost/a".$durl;
}

[/php]

转载请注明来自微度网络,本文标题:《短网址的原理解析》

喜欢 0 发布评论
Top