php 生成短網(wǎng)址原理及代碼
更新時(shí)間:2014年01月23日 17:05:11 作者:
將原網(wǎng)址做crc32校驗(yàn),得到校驗(yàn)碼,使用sprintf將校驗(yàn)碼轉(zhuǎn)為無(wú)符號(hào)數(shù)字,詳細(xì)步驟請(qǐng)看本文
php 生成短網(wǎng)址
原理:
1.將原網(wǎng)址做crc32校驗(yàn),得到校驗(yàn)碼。
2.使用sprintf('%u') 將校驗(yàn)碼轉(zhuǎn)為無(wú)符號(hào)數(shù)字。
3.對(duì)無(wú)符號(hào)數(shù)字進(jìn)行求余62操作(大小寫字母+數(shù)字等于62位),得到余數(shù)后映射到62個(gè)字符中,將映射后的字符保存。(例如余數(shù)是10,則映射的字符是A,0-9對(duì)應(yīng)0-9,10-35對(duì)應(yīng)A-Z,35-62對(duì)應(yīng)a-z)
4.循環(huán)操作,直到數(shù)值為0。
5.將所有映射后的字符拼接,就是短網(wǎng)址后的code。
代碼如下:
/** 生成短網(wǎng)址
* @param String $url 原網(wǎng)址
* @return String
*/
function dwz($url){
$code = sprintf('%u', crc32($url));
$surl = '';
while($code){
$mod = $code % 62;
if($mod>9 && $mod<=35){
$mod = chr($mod + 55);
}elseif($mod>35){
$mod = chr($mod + 61);
}
$surl .= $mod;
$code = floor($code/62);
}
return $surl;
}
原理:
1.將原網(wǎng)址做crc32校驗(yàn),得到校驗(yàn)碼。
2.使用sprintf('%u') 將校驗(yàn)碼轉(zhuǎn)為無(wú)符號(hào)數(shù)字。
3.對(duì)無(wú)符號(hào)數(shù)字進(jìn)行求余62操作(大小寫字母+數(shù)字等于62位),得到余數(shù)后映射到62個(gè)字符中,將映射后的字符保存。(例如余數(shù)是10,則映射的字符是A,0-9對(duì)應(yīng)0-9,10-35對(duì)應(yīng)A-Z,35-62對(duì)應(yīng)a-z)
4.循環(huán)操作,直到數(shù)值為0。
5.將所有映射后的字符拼接,就是短網(wǎng)址后的code。
代碼如下:
復(fù)制代碼 代碼如下:
/** 生成短網(wǎng)址
* @param String $url 原網(wǎng)址
* @return String
*/
function dwz($url){
$code = sprintf('%u', crc32($url));
$surl = '';
while($code){
$mod = $code % 62;
if($mod>9 && $mod<=35){
$mod = chr($mod + 55);
}elseif($mod>35){
$mod = chr($mod + 61);
}
$surl .= $mod;
$code = floor($code/62);
}
return $surl;
}
相關(guān)文章
php+Memcached實(shí)現(xiàn)簡(jiǎn)單留言板功能示例
這篇文章主要介紹了php+Memcached實(shí)現(xiàn)簡(jiǎn)單留言板功能,結(jié)合實(shí)例形式較為詳細(xì)的分析了php結(jié)合memcached實(shí)現(xiàn)留言板的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-02-02php使用curl實(shí)現(xiàn)簡(jiǎn)單模擬提交表單功能
這篇文章主要為大家詳細(xì)介紹了php使用curl實(shí)現(xiàn)簡(jiǎn)單模擬提交表單功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05PHP setcookie設(shè)置Cookie用法(及設(shè)置無(wú)效的問(wèn)題)
平時(shí)用Session比較多,很少用到Cookie,這次是為了解決Discuz!自動(dòng)同步登陸不得不用Cookie。2011-07-07