Base N to 10 Conversion Class - PHP (Base 62 Implementation)
This class can be used convert a base N number into base 10, and back. (Which makes it ideal for usage in technologies such as URL shorteners.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <?php /** * BNID - Base N <=> 10 converter * * @author kenny cason * @site www.ken-soft.com */ class BNID { // Alphabet of Base N (This is a Base 62 Implementation) var $bN = array( '0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' ); // Alphabet of Base 86 (comment out the B62 array and comment this to try it out) /*var $bN = array( '0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', '-','+','_','%','|','@','!','$','*','~','`','#','(',')','=','&','[',']','{','}','<','>',':',';' );*/ var $baseN; function __construct() { $this->baseN = count($this->bN); } // convert base 10 to base N function base10ToN($b10num=0) { $bNnum = ""; do { $bNnum = $this->bN[$b10num % $this->baseN] . $bNnum; $b10num /= $this->baseN; } while($b10num >= 1); return $bNnum; } // convert base N to base 10 function baseNTo10($bNnum = "") { $b10num = 0; $len = strlen($bNnum); for($i = 0; $i < $len; $i++) { $val = array_keys($this->bN, substr($bNnum, $i, 1)); $b10num += $val[0] * pow($this->baseN, $len - $i - 1); } return $b10num; } } /* // test, uncomment and call this script to demonstrate it's functionality $conv = new BNID(); $max = pow($conv->baseN, 2); for($i = 0; $i <= $max; $i++) { echo $conv->base10ToN($i).", "; } echo "<br/><br/>"; for($i = 0; $i <= $max; $i++) { $x = $conv->base10ToN($i); echo $conv->baseNTo10($x).", "; } */ ?> |
If you want to use this as a URL shortener, below is a quick demo of how to use URL Rewrite to accept www.page.com/
place the below text in .htaccess in your websites root directory
Options +FollowSymlinks
RewriteEngine on
RewriteBase /yourrootdirectory/
RewriteRule ^(([A-Z]*[a-z]*[0-9]*)*)$ main.php?b62id=$1 [L,QSA]
So it should take a domain www.abc.com, if you specify www.abc.com/zA4F, it would forward to www.abc.com/main.php?id=14576711
Here is a sample Demohttp://www.ken-soft.com/code/php/baseconvert/AABCz23












