PHP微博客应用中的URL缩短类
在Unix机上的PHP脚本 .class.php可以复用 下面有4个方法用来缩短 加密 解密 DB中的原始URL 并缩短他
结合Apache的rewrite模块进行路由
如传入一个http://index.php/catagory/python-cookbook_3tdedition.php
重写为..index.php/123/512.html
在Apache模块中可以定义 catagory请求为123路由地址
因为是用的单例模式的CONN 处理并发请求 测试的时候MySQL 并发命中会很低
#!usr/local/bin/php <?php /** * 使用单例模式 4个方法 编码 解码 测试 压缩URL * SQL表urls只有2个字 一个自增长的ID 一个varchar的url字符串 * 512增加为了防止传入的url太短 * */ class UrlShortener { const OFFSET = 512; private $base; private $characterMap; public function __construct(){ //初始化私有变量 $this->characterMap = array( '1','2','3','4','5','6','7','8','9', 'z','x','c','b','v', 'f','g','h','j','k','L','m','n', 'q','w','r','t','y','p','s','d' ); $this->base = sizeof($this->characterMap); } public static function getInstance(){ static $instance = null; if($instance === null){ $instance = new UrlShortener(); } return $instance; } public function shorten($conn,$url){ $escapedUrl = mysql_escape_string($url); $res = mysql_query("select 'id' from urls where 'url' like $escapedUrl",$conn); $row = mysql_fetch_row($res); mysql_free_result($res); //如果有 就进行编码 然后重写进入数据库 if($row) return $this->encode($row[0]+self::OFFSET); //如果没有 就先编码后插入 $res = mysql_query(" insert into 'urls'('url') values('$escapedUrl') ",$conn); return $this->encode(mysql_insert_id($conn)+self::OFFSET); } public function encode($val){ #递归对每一个URL中的字符进行解码 #@return 解码以后的字符串Url $val += 512; if($val < $this->base){ return $this->characterMap[ $val ]; }else{ return $this->encode(floor( $val/$this->base)). $this->characterMap[ $val % $this->base]; } } public function decode($val){ $decodeMap = array_flip($this->characterMap);#翻转字典 $parts = array_reverse(str_split( $val )); $index = 0; $i = 0; foreach($parts as $part){ $index += $decodeMap[$part] * pow($this->base,$i++); } return $index-512; } public function expand($conn,$index){ $id = $this->decode($index)-self::OFFSET; $res = mysql_query(' select "url" from "urls" where 'id' = $id ',$conn); $value = (($row = mysql_fetch_row( $res)))?$row[0]:null; mysql_free_result($res); return $value; } }#end class ?>
2. [文件] test4Url.php
#!/usr/local/bin/php <?php //测试一下上面的class include ( "UrlShortener.class.php" ) $shortener = UrlShortener::getInstance(); set_time_limit(0); $stdin = fopen("php://stdin",'r'); while(1){ $index = trim(fgets($stdin)); return $shortener->expand(getDb(),$index).'\n'; } function getDb(){ static $db = null; if(!$db||!mysql_ping($db){ $db = mysql_connect('localhost','user','password'); mysql_select_db("test"); } return $db; } ?>
以上就是PHP微博客应用中的URL缩短类 的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!