博客小子:记录我们对互联网和生活的探索! 注册 | 登陆

我也来说说php+mysql实现仿微博短网址跳转功能

Tags: php, mysql, 短网址, 跳转

相信很多朋友对微博里面的短网址跳转有恍然印象吧。下面说说怎么用实现这个功能。转载请注明来源www.blogguy.cn

首先创建一个表,结构如下:

CREATE TABLE `bogguy_cn_url` (
  `id` bigint(12) NOT NULL AUTO_INCREMENT,
  `url` varchar(1000) DEFAULT NULL,
  `click` bigint(10) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `url` (`url`(500))
) ENGINE=MyISAM AUTO_INCREMENT=1DEFAULT CHARSET=gbk;

这个表是用来存储地址的。

然后使用如下代码来加密原有链接。

例子是:

$pub_info="我要发微博 问一好友相册密码是多少,他给了我一大串英文字母'cptbtptpbcptdtptp'。我惊讶地问:这么长,你咋记得住啊? 他回:吃葡萄不吐葡萄皮不吃葡萄倒吐葡萄皮! http://www.blogguy.cn/show-787-1.html ";
$pattern ="/http:\/\/?[\w:\/\.\?=&-_]+/is";
preg_match($pattern, $pub_info, $url);
$url=$url[0];
if($url){
 $urldatabase=addslashes ($url);
 $query=$GLOBALS['db']->query("insert into bo_url(url) values ('$urldatabase')");
 $id=$GLOBALS['db']->insert_id();
 $shorturl="http://www.blogguy.cn/".dec2any($id);
 $pub_info=str_replace($url,$shorturl,$pub_info);
}
//echo($pub_info);

至此,生成短网址解决了,下面是短网址转发,首先设置htaccess跳转:

apache设置如下:

 RewriteEngine on
 RewriteBase /
 RewriteRule ^([a-z0-9\-]+)$ index.php?co=$1 [L]

nginx如下设置:

 rewrite ^/([a-z0-9\-]+)$ /index.php?co=$1 last;

转载请注明来自www.blogguy.cn,鄙视盗窃的人。接下来写一个index.php文件,内容大致如下:

if($_GET["u"]){
  $id=any2dec($_GET["u"]);
  mysql_connect("localhost", "root", "") or
   die("Could not connect: " . mysql_error());
  mysql_select_db("blogguy_cn");
  $result = mysql_query("SELECT url FROM bogguy_cn_url where id=$id limit 0,1");
  $row = mysql_fetch_array($result, MYSQL_NUM);
  $url=$row[0];
  if($url) mysql_query("update bogguy_cn_url set click=click+1 where id=$id");
  header('Location: '.$url.'', TRUE, 301);

}else{
 //没有接收数据
}

功能基本上就完成了,说得有点断断续续的,相信有点基础的朋友都可以看明白。

最后补充两个函数,转化进制用的,本例中有用到。

//十进制转到其他制
function dec2any( $num, $base=62, $index=false ) {
    if (! $base ) {
        $base = strlen( $index );
    } else if (! $index ) {
        $index = substr( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0 ,$base );
    }
    $out = "";
    for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) {
        $a = floor( $num / pow( $base, $t ) );
        $out = $out . substr( $index, $a, 1 );
        $num = $num - ( $a * pow( $base, $t ) );
    }
    return $out;
}

function any2dec( $num, $base=62, $index=false ) {
    if (! $base ) {
        $base = strlen( $index );
    } else if (! $index ) {
        $index = substr( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base );
    }
    $out = 0;
    $len = strlen( $num ) - 1;
    for ( $t = 0; $t <= $len; $t++ ) {
        $out = $out + strpos( $index, substr( $num, $t, 1 ) ) * pow( $base, $len - $t );
    }
    return $out;
}

 

很久没有写博客了,主要是我没有多少时间,而且现在看sablog的功能不是很能满足我,灌水机太多,我都没有心情去删除垃圾。

Tags: php, mysql, 短网址, 跳转

« 上一篇:xampp安装后apache不执行php的重大事故 | 下一篇:discuzx1.5加上仿铁血网的图片上传下面加一个黑白条的水印 »

只显示10条记录相关文章

Trackbacks

点击获得Trackback地址,Encode: UTF-8

发表评论

评论内容 (必填):