찾다
php教程PHP源码PHP微博客应用中的URL缩短类

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(
			&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,
			&#39;z&#39;,&#39;x&#39;,&#39;c&#39;,&#39;b&#39;,&#39;v&#39;,
			&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;j&#39;,&#39;k&#39;,&#39;L&#39;,&#39;m&#39;,&#39;n&#39;,
			&#39;q&#39;,&#39;w&#39;,&#39;r&#39;,&#39;t&#39;,&#39;y&#39;,&#39;p&#39;,&#39;s&#39;,&#39;d&#39;
		);
		$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 &#39;id&#39; from urls where &#39;url&#39; 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 &#39;urls&#39;(&#39;url&#39;) values(&#39;$escapedUrl&#39;)
			",$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(&#39;
			select "url" from "urls" where &#39;id&#39; = $id
			&#39;,$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",&#39;r&#39;);

while(1){
	$index = trim(fgets($stdin)); 
	return $shortener->expand(getDb(),$index).&#39;\n&#39;;
}

function getDb(){
	static $db = null;
	if(!$db||!mysql_ping($db){
		$db = mysql_connect(&#39;localhost&#39;,&#39;user&#39;,&#39;password&#39;);
		mysql_select_db("test");
	}
	return $db;
}

?>

 以上就是PHP微博客应用中的URL缩短类 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.