IDs are often numbers. Unfortunately there are only 10 digits to work with, so if you have a lot of records, IDs tend to get very lengthy. For computers that’s OK. But human beings like their IDs as short as possible. So how can we make IDs shorter? Well, we could borrow characters from the alphabet as have them pose as additional numbers…. Alphabet to the rescue!
Other title options where
- How to create unique short string IDs with PHP & MySQL
- Or how to create IDs similar to YouTube e.g. yzNjIBEdyww
I created this function a long time ago. Time to be nice and share.
More is Less - the ‘math’
The alphabet has 26 characters. That’s a lot more than 10 digits. If we also distinguish upper- and lowercase, and add digits to the bunch or the heck of it, we already have (26 x 2 + 10) 62 options we can use per position in the ID.
Now of course we can also add additional funny characters to ‘the bunch’ like - / * & # but those may cause problems in URLs and that’s our target audience for now.
OK so because there are roughly 6x more characters we will use per position, IDs will get much shorter. We can just fit a lot more data in each position.
This is basically what url shortening services do like tinyurl, is.gd, or bit.ly. But similar IDs can also be found at youtube: http://www.youtube.com/watch?v=yzNjIBEdyww
Convert your IDs
Now unlike Database servers: webservers are easy to scale so you can let them do a bit of converting to ease the life of your users, while keeping your database fast with numbers (MySQL really likes them plain numbers ; )
To do the conversion I’ve written a PHP function that can translate big numbers to short strings and vice versa. I call it: alphaID.
The resulting string is not hard to decipher, but it can be a very nice feature to make URLs or directorie structures more compact and significant.
So basically:
- when someone requests rLHWfKd
- alphaID() converts it to 999999999999
- you lookup the record for id 999999999999 in your database
Source
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
Example
Running:
1
| |
will return PpQXn7COf and:
1
| |
will return 9007199254740989
Easy right?
More features
- There also is an optional third argument:
$pad_up. This enables you to make the resulting alphaId at least X characters long. - You can support even more characters (making the resulting alphaID
even smaller) by adding characters to the
$indexvar at the top of the function body.
Bonus
Thanks to some wonderful contributions in the comment section, here are some interesting updates & additions:
Pro tip
You may want to remove vouwels (a, e, o, u, i) from $index
as to avoid combinations that result in: ‘penis’ or other dirty words
that could get your customers upset.
You can also use the $pad_up argument to enforce a minimum length
of 5 characters as to avoid: ‘nsfw’ and ‘wtf’.
Thanks to William for pointing this out ; )
Postgres Implementation
Thanks to William as well:
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 | |
Java Implementation
Thanks to Ant Kutschera there also is a Java version.
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
JavaScript Implementation
Thanks to Even Simon, there’s a JavaScript implementation. You will also find PHP version there, that implements the encode & decode functions as separate methods in a class.
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
C# Implementation
Thanks to Romas, there’s a C# implementation.
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 | |
Python Implementations
Thanks to wessite, there’s a Python implementation.
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 | |
Noah Miller contributed a version based on Wessite’s, and changed it so it can use a passkey, and rolled it into one function:
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 | |
HaXe Implementation
Thanks to Andy Li, there’s a HaXe implementation.
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 | |
Imported comments
These were imported from my old blog. Please use disqus below for new comments
Aamir
on 2012-09-17 15:04:57
It’s a really very informative information. It’s very useful and knowledgeable for me. I will bookmark this page and come soon to see the updates.
maria queen
on 2012-09-09 21:57:12
maza
David
on 2012-08-19 04:20:20
What about creating unique ID’s from alpha-numeric ones? I’m getting `A non well formed numeric value encountered` on your solution
HBR
on 2012-08-11 16:40:45
Hi,
Thank you for this useful function. I have a question about it (since i’m bad at maths !).
Actually, users in my application will encrypt IDs using a pass. If the pass is hardcoded by me and implicitly shared by all of them, the resulting encrypted alphid will look like &
quot;ab3g, cd3g, kj3g&
quot; for IDs like &
quot;8081, 8082, 8083&
quot;.
I wouldn’t like them to look like a sequence, it is better in my case to have &
quot;hJ39, cd3K, oPI3&
quot; for the same sequence of ID 8081, 8082, 8083…
So my question is, given an auto_increment ID in a mysql table, if I use a user-specific unique random pass key to encrypt each ID (and then decrypt it), is there a risk of collision ?
I hope my question is clear …
Thanks
Bill
on 2012-07-31 14:33:55
@Leander (cc @Renox)
Your solution not return a same length string for $alphaId.
fetr
on 2012-07-27 14:52:36
very nice
Renox
on 2012-05-13 12:42:02
@ Leander
nice ^^
typical for php btw.
Someone implements a big function of something, that already exists.
Leander
on 2012-05-09 16:10:33
to me this seems quite complicated.
why not just express your integer with a base of lets say 36?
$testId = 9999999999999;
$alphaId = base_convert($testId, 10, 36);
$originalInteger = intval($alphaId, 36);
SaudSattar
on 2012-03-24 08:52:47
Good
Lan
on 2012-02-19 20:23:18
@ Dan: 238328
You can calculate this by
(length of $index) ^ (number of places)
so 62^3 = 238,328
Using 4 places would give you 14,776,336 numbers to work with
wouter2512
on 2012-02-16 15:46:15
@Alessandro
That aren’t duplicates, but rather your checking is not in order. PHP interprets the values 0x… as hexadecimal and searches for the corresponding value. And as it happends it exists already… It also happens with strings starting with 1e… and so on.
Necessity
on 2012-02-09 17:23:00
What inputs am I allowed to use if my output must be exactly a 6 digit number?
Rafique
on 2012-02-03 10:50:12
Thnks alot bro!! it helps alot!! :)
Romas
on 2012-01-17 09:38:54
C# code:
class ShortId
{
public string Alphabet = &
quot;abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ&
quot;;
public string Encode(Int64 Number)
{
string result = String.Empty;
for (int i = (int)Math.Floor(Math.Log(Number) / Math.Log(Alphabet.Length)); i &
gt;= 0; i–)
{
result += Alphabet.Substring((int)(Math.Floor(Number / BcPow(Alphabet.Length, i)) % Alphabet.Length), 1);
}
return ReverseString(result);
}
public Int64 Decode(string Id)
{
string str = ReverseString(Id);
Int64 result = 0;
int end = str.Length - 1;
for (int i = 0; i &
lt;= end; i++)
{
result = result + (Int64)(Alphabet.IndexOf(str.Substring(i, 1)) * BcPow(Alphabet.Length, end - i));
}
return result;
}
public double BcPow(double _a, double _b)
{
return Math.Floor(Math.Pow(_a, _b));
}
public string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
Alessandro
on 2011-11-16 11:08:06
Hi, thank you for your nice script, i’m testing it with this script:
$test=Array();
for($i=1000000;$i&
lt;9007199254740992;$i++){
$id = alphaID($i, false, 8);
if (in_array($id, $test)) {
echo &
quot;Collision detected at $i with id $id\n&
quot;;
}
if($i % 1000 == 0){
echo &
quot;i = $i\n&
quot;;
}
array_push($test,$id);
}and it seems that there are some collisions all starting with 0X, is there a starting number that can be considered & quot;safe& quot;? Because you won’t create an id that corrispond to 2 rows in the db.
Best Regards
dahuda
on 2011-11-03 13:18:34
Code seems nice, will use it .. thnx in advance man. keep up the good work, it is appreciated..
Tim
on 2011-09-23 00:06:37
With smaller ids and padding this creates not so random hashes. Anyway around this?
2 = dbbbc
3 = fbbbc
Neil
on 2011-08-11 08:05:35
I also remove lowercase L, the number 1, the letter O and Zero, because they can be ambiguous if you need to physically type them.
sid
on 2011-07-07 09:20:04
How do you think duplicate alphaid’s can be avoided without correlating with a auto_increment field ?
Rony
on 2011-06-28 18:32:14
Really great function. Saved me a lot of coding. :)
Thanks…
sylvester javed
on 2011-06-21 16:02:57
the best viewer page
sameer zafar
on 2011-06-11 14:35:51
rehgsfgfh
Dan
on 2011-05-18 13:49:31
That’s a great function.
How many combinations are if I choose the string to be of length 3?
Is it more than 1 million?
Or how could I calculate.
Thanks.
Kevin
on 2011-04-17 16:40:36
@ franfran: That’s expected behavior. I guess if you take out the part where I reverse the string, it could work without knowing the padlength.
@ chrischris: I’ll need to look into that
franfran
on 2011-04-11 08:07:26
Thanks, this is a nice function. However, just found out that you must know the $pad_up value to decode. So the $pad_up is somehow become part of the $passKey.
If we want to encode a string with minimum length:
alphaID(9007199254740989, false, 6);
will return ‘9QFqnGSNRf’
alphaID('9QFqnGSNRf', true);
will get the WRONG thing 9007199599766240
You can only get back the original number if you know the $pad_up
alphaID('9QFqnGSNRf', true, 6);
will return 9007199254740989
chrischris
on 2011-04-07 20:13:18
Hi Kevin,
Thanks for a great script. Thanks!
Have you considered using the input as a string instead of an integer to overcome the limitation of a large integer in PHP?
&
quot;18446744073709551615&
quot; instead of 18446744073709551615.
I’ve been playing around with this encryption class by Tony Marston (http://www.tonymarston.co.uk/php-mysql/encryption.html), and it seems it works even with 18446744073709551615.
But the trick is you have to make sure the input is a string. If it’s integer and the number is very large, PHP will convert it into a scientific notation e.g. 1.84467440E+12 first, and the encryption class will use this scientific notation instead of the actual number representation for conversion.
And you’d need to tweak the class so the resulted data is URL friendly. I just removed all the funny characters, except an empty space &
quot; &
quot; because it’s used for padding. And then I added a code to replace a &
quot; &
quot; with a &
quot;_&
quot; to make it URL friendly. When I need to decode it, I just replace &
quot;_&
quot; back to &
quot; &
quot; before decoding it. It seems it works fine.
–
As for your alphaID script, is there a limitation with $pad_up? When I set it to 10, some numbers don’t get converted back correctly:
for($i = 0; $i &
lt; 100; $i++){
$alpha_id = alphaID($i, false, 10, &
quot;passtest&
quot;);
$int_id = alphaID($alpha_id, true, 10, &
quot;passtest&
quot;);
print &
quot;$i|$alpha_id|$int_id&
lt;br&
gt;&
quot;;
}
Results:
Original int|alphaID|Converted int back
0|2222222229|0
1|2222222229|0
2|A222222229|2
3|R222222229|4
4|R222222229|4
5|R222222229|4
6|0222222229|6
7|W222222229|8
8|W222222229|8
9|W222222229|8
Thanks.
devashish gupta
on 2011-03-13 08:18:38
i like………
Kevin
on 2011-03-10 14:44:36
@ John Smith: But then how would you encode 0? ; )
If you’ll never use zeros, I guess an easy &
quot;fix&
quot; for that would be in your call: alphaID($mynumber-1).
Don’t forget to reverse the decrement when you’re decoding as well.
John Smith
on 2011-03-10 06:31:14
Thanks for sharing! Everything works perfect, except for that when the ID is 1, the code uses &
quot;b&
quot; not &
quot;a&
quot;, and when the ID is 63, it uses &
quot;bb&
quot; not &
quot;aa&
quot;. Is there any fix for that?
Kevin
on 2011-03-04 13:13:39
@ cdub: Thanks : ) Url doesn’t seem to work anymore though :/
@ Iain: As stated in the function’s comments, it’s limited to relatively small numbers (9007199254740989 on 32bits systems). If you need anything bigger you’d best make some adjustments using the bc extension in PHP
Iain
on 2011-02-24 13:11:10
I like this very much. But it gives an error result with large number. Here is an example:
$num = 18446744073709551615; // mysql unsigned int
// print MOrkgbArGYv
$converted = alphaID($num);
// print 18446744073709551616
echo alphaID($converted, true);
Notice there is a slight difference there on the result. Anyone can help on this issue?
Thanks.
cdub
on 2011-01-11 20:25:24
One more thing… I found an ASP.NET MVC url shortener similar to yours and thought it might be useful to link here, http://blog.andresays.org/2010/11/simple-url-shortening-with-rolling-strings/
Ganesh
on 2011-01-10 20:27:41
shall we use base_convert?
cdub
on 2011-01-10 08:14:00
Thanks so much! I’ve done a lot of research on URL shorteners and I like you’re implementation the best.
Julien
on 2010-12-30 15:56:17
I tried PHP and Python solution but the short ID created with int ID are not the same.
Martin
on 2010-11-11 12:23:39
Very nice.
Kevin
on 2010-06-10 20:50:07
@ Stephen: Not that I mind uniform results, but that's still an excellent tip I imagine many will find very useful. Thanks!
@ Tim: You're note supposed to do anything. But I would just use numeric indexes to keep the database speedy, and use appservers (easiest to scale in any infra) to care care of the conversion. If you don't want small alphaIds like 'c', try the pad argument.
Tim
on 2010-05-23 16:27:10
Could you give an example of putting it all together with PHP/mySQL, including table structure?
I'm building a new site and don't have big numbers yet. So if I set my ID column to make up a big number, such as INT(16) unsigned zerofill and INSERT a record, I get 0000000000000001 as an id. If I return that using the alphaID() function I get 'c'. Hardly usable. :)
Are we supposed to add a second id column, alpha_id INT(16), instead and have PHP generate a random number, then INSERT IGNORE and hope that the number already isn't in the db? Or are we supposed to store the alphaID \&
quot;PpQXn7COf\&
quot; in the db and lookup on that? If so, doesn't that then negate the speed of a numerical lookup? Also, that just goes back to having PHP generate a rand number, right?
Stephen
on 2010-05-22 12:59:14
Gr8 script.
I thought I might add to it. If you have a short number and the pad_up say alphaID('9', false, 7, 'passkeys') you get a number like 366666P.
to avoid having something uniform like this I multiply the
(Digital number –&
gt;&
gt; alphabet letter code)
by a large prime number.. eg: $in = $in * 89527;
and you need to do the rev also so at the end of
(Digital number &
lt;&
lt;– alphabet letter code):
$out = $out / 89527;
This will produce a more cryptic output like YDPH66P.
As for the prime number I just went and picked one from http://www.mathsisfun.com/numbers/prime-number-lists.html
Kevin
on 2010-05-15 19:11:11
@ SD (Aspherical): No problem
@ esco: Yeah you need the bcmath stuff.
@ Webdesigner: while it was not intended to encrypt or hide the actual id so much as to make it smaller/easier to read, Simon Franz patched the function to support passwords. the 4th argument.
esco
on 2010-05-07 01:29:24
I had to install bcmath extension. Works fine now. If anyone has the same problem, check your php configuration.
Webdesigner
on 2010-05-02 17:43:27
How to add a secure Passwort, so that it's harder to get the ID from the String?
esco
on 2010-05-01 22:11:07
No return when I try for example
echo alphaID(238328, false);When I try to debug a bit amateuristic, I think it breaks at:
$bcp = bcpow($base, $t);Can someone help?
SD (Aspherical)
on 2010-04-30 04:52:47
Thanks so much for posting this, I used your digital number to alphabet letter encoding code section to build a custom link shortener that I use when Twittering my photoblog updates. Works like a charm!
Right now, I just put the encoded link in a database table, but I might explore using the decoder in the future.
Kevin
on 2010-04-24 10:27:18
@ Andy Li: Awesome, Added! :)
Thiet ke website
on 2010-04-19 09:30:33
Thanks for the nice code, i'm very interesting :)
Andy Li
on 2010-04-06 21:54:10
I made a haXe version, which can be compiled to swf/js/php/c++/neko :)
Here it is:
http://gist.github.com/358018
Kevin
on 2010-04-04 17:13:39
@ wessite: How cool is that?? Thanks, Added! : )
wessite
on 2010-03-31 17:27:14
Thanks for this article, the code was very useful!
I needed this in python to use on Google Appengine, here's the code:
ALPHABET = \&
quot;bcdfghjklmnpqrstvwxyz0123456789BCDFGHJKLMNPQRSTVWXYZ\&
quot;
BASE = len(ALPHABET)
MAXLEN = 6
def encode_id(self, n):
pad = self.MAXLEN - 1
n = int(n + pow(self.BASE, pad))
s = []
t = int(math.log(n, self.BASE))
while True:
bcp = int(pow(self.BASE, t))
a = int(n / bcp) % self.BASE
s.append(self.ALPHABET[a:a+1])
n = n - (a * bcp)
t -= 1
if t &
lt; 0: break
return \&
quot;\&
quot;.join(reversed(s))
def decode_id(self, n):
n = \&
quot;\&
quot;.join(reversed(n))
s = 0
l = len(n) - 1
t = 0
while True:
bcpow = int(pow(self.BASE, l - t))
s = s + self.ALPHABET.index(n[t:t+1]) * bcpow
t += 1
if t &
gt; l: break
pad = self.MAXLEN - 1
s = int(s - pow(self.BASE, pad))
return int(s)
Kevin
on 2010-03-27 13:56:22
@ William: Hey there! Good stuff man! I've updated the article to reflect your awesome contributions!
William
on 2010-03-27 12:58:45
Hey Kevin and others!
In my last comment I suggested to remove all vowels from $index to prevent unfriendly / dirty words. With that in mind I would like to add another suggestion: to make the string at least 5 characters long to prevent getting id's like: 'wtf', 'nsb', 'nsfw', etc ;-)
I also made a PostgreSQL version of Kevin's script :-)
It doesn't create a random unique string, but it will convert numbers to a string. It's an edited version of base64 encoding (URL save version without characters like: '/' and '=' ).
I hope you people find any use for it.
&
lt;?php
CREATE OR REPLACE FUNCTION string_to_bits(input_text TEXT)
RETURNS TEXT AS $$
DECLARE
output_text TEXT;
i INTEGER;
BEGIN
output_text := '';
FOR i IN 1..char_length(input_text) LOOP
output_text := output_text || ascii(substring(input_text FROM i FOR 1))::bit(8);
END LOOP;
return output_text;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION id_to_sid(id INTEGER)
RETURNS TEXT AS $$
DECLARE
output_text TEXT;
i INTEGER;
index TEXT[];
bits TEXT;
bit_array TEXT[];
input_text TEXT;
BEGIN
input_text := id::TEXT;
output_text := '';
index := string_to_array('0,d,A,3,E,z,W,m,D,S,Q,l,K,s,P,b,N,c,f,j,5,I,t,C,i,y,o,G,2,r,x,h,V,J,k,-,T,w,H,L,9,e,u,X,p,U,a,O,v,4,R,B,q,M,n,g,1,F,6,Y,_,8,7,Z', ',');
bits := string_to_bits(input_text);
IF length(bits) % 6 &
lt;&
gt; 0 THEN
bits := rpad(bits, length(bits) + 6 - (length(bits) % 6), '0');
END IF;
FOR i IN 1..((length(bits) / 6)) LOOP
IF i = 1 THEN
bit_array[i] := substring(bits FROM 1 FOR 6);
ELSE
bit_array[i] := substring(bits FROM 1 + (i - 1) * 6 FOR 6);
END IF;
output_text := output_text || index[bit_array[i]::bit(6)::integer + 1];
END LOOP;
return output_text;
END;
$$ LANGUAGE plpgsql;
?&
gt;
Have a nice day!
William
Kevin
on 2010-03-24 10:06:45
@ William: Fair point : ) Thanks for this.
@ Even Simon: Good stuff man!
@ both: I'll update the article with clear references to your comments soon
Even Simon
on 2010-03-23 13:17:24
Hi there,
I've used your code for my website, let me say this is some excellent work. Anyhow I also needed the same functionality on the client-side (JavaScript) so I had to write my own. Here it is:
/**
* Javascript AlphabeticID class
* (based on a script by Kevin van Zonneveld &
lt;kevin@vanzonneveld.net&
gt;)
*
* Author: Even Simon &
lt;even.simon@gmail.com&
gt;
*
* Description: Translates a numeric identifier into a short string and backwords.
*
* Usage:
* var str = AlphabeticID.encode(9007199254740989); // str = \'fE2XnNGpF\'
* var id = AlphabeticID.decode(\'fE2XnNGpF\'); // id = 9007199254740989;
**/
var AlphabeticID = {
index:\'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\',
/**
* @function AlphabeticID.encode
* @description Encode a number into short string
* @param integer
* @return string
**/
encode:function(_number){
if(\'undefined\' == typeof _number){
return null;
}
else if(\'number\' != typeof(_number)){
throw new Error(\'Wrong parameter type\');
}
var ret = \'\';
for(var i=Math.floor(Math.log(parseInt(_number))/Math.log(AlphabeticID.index.length));i&
gt;=0;i--){
ret = ret + AlphabeticID.index.substr((Math.floor(parseInt(_number) / AlphabeticID.bcpow(AlphabeticID.index.length, i)) % AlphabeticID.index.length),1);
}
return ret.reverse();
},
/**
* @function AlphabeticID.decode
* @description Decode a short string and return number
* @param string
* @return integer
**/
decode:function(_string){
if(\'undefined\' == typeof _string){
return null;
}
else if(\'string\' != typeof _string){
throw new Error(\'Wrong parameter type\');
}
var str = _string.reverse();
var ret = 0;
for(var i=0;i&
lt;=(str.length - 1);i++){
ret = ret + AlphabeticID.index.indexOf(str.substr(i,1)) * (AlphabeticID.bcpow(AlphabeticID.index.length, (str.length - 1) - i));
}
return ret;
},
/**
* @function AlphabeticID.bcpow
* @description Raise _a to the power _b
* @param float _a
* @param integer _b
* @return string
**/
bcpow:function(_a, _b){
return Math.floor(Math.pow(parseFloat(_a), parseInt(_b)));
}
};
/**
* @function String.reverse
* @description Reverse a string
* @return string
**/
String.prototype.reverse = function(){
return this.split(\'\').reverse().join(\'\');
};
Plus I've rewritten your PHP function into a PHP class to make it more suitable for my code:
&
lt;?php
class AlphabeticID{
const index = \&
quot;abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\&
quot;;
public static function encode($number){
if(!isset($number)){
return null;
}
$base = strlen(self::index);
$out = \&
quot;\&
quot;;
for ($t = floor(log($number, $base)); $t &
gt;= 0; $t--) {
$bcp = bcpow($base, $t);
$a = floor($number / $bcp) % $base;
$out = $out . substr(self::index, $a, 1);
$number = $number - ($a * $bcp);
}
$out = strrev($out);
return $out;
}
public static function decode($string){
$base = strlen(self::index);
$string = strrev($string);
$out = 0;
$len = strlen($string) - 1;
for ($t = 0; $t &
lt;= $len; $t++){
$bcpow = bcpow($base, $len - $t);
$out = $out + strpos(self::index, substr($string, $t, 1)) * $bcpow;
}
$out = sprintf(\'%F\', $out);
$out = substr($out, 0, strpos($out, \'.\'));
return $out;
}
}
?&
gt;
Have a nice day. $))
-Simon
William
on 2010-03-22 12:56:26
Nice script!
I got 1 small advise.. Remove all vouwels (a, e, o, u, i) from $index, otherwise one day one of your customers will ask you why his username (or whatever) is 'penis' (or another unfriendly/dirty word) ;-).
Kevin
on 2010-02-21 16:38:55
@ Ant Kutschera: Cool to see someone tackling the exact same problem in a completely different part of the world &
amp; programming community :) Thanks for leaving a note man.
Ant Kutschera
on 2010-02-13 22:59:19
hi,
ive done the same thing independently using java.
http://blog.maxant.co.uk/pebble/2010/02/02/1265138340000.html
im not sure what this type of encoding is really called…
another application for it is where you want to provide users with a pin which they can share among friends. but you dont want anyone to guess the pin. so you take your primary key for the relevant thing which is being shared, and append a 4 digit random number the the end, before encoding your big number. the PIN you distribute is the encoded shorter version.
Kevin
on 2010-01-07 18:53:50
@ Catalin: Good point. With my distro it's default, but that may not be the case for everybody. Thanks for sharing.
Catalin
on 2009-12-17 09:00:27
php must be compiled with –enable-bcmath configure option for this to work.
Kevin
on 2009-12-13 17:33:41
@ Deadfish: Wow great stuff! I've fixed the bug thanks!
http://github.com/kvz/kvzlib/commit/1bf020eb82fcfac67353219817b3813e2df325e5
Deadfish
on 2009-12-08 11:30:41
A proper bug fix…
replace log10($in) / log10($base) with log10($in, $base) and $a = floor($in / $bcp) with $a = floor($in / $bcp) % $base. That will fix the bug with alphaID(238328);
Deadfish
on 2009-12-07 21:37:36
The only example I can find of this bug happening is alphaID(238328);
Deadfish
on 2009-12-07 20:42:57
I think there is a bug in your code. I believe it should not be… $base = strlen($index); but $base = strlen($index) - 1; or else during encoding when it calls substr($index, $a, 1) $a would be the character after the last character. Apart from that great code :D
Kevin
on 2009-10-25 14:16:51
@ Tanzmusik: Well it was never the goal of this function to be used as a security measure, but Simon Franz was kind enough to provide a patch for that nonetheless:
http://github.com/kvz/kvzlib/commit/323e9c3bb3e489150bdddea51a785e1e931003d7
Tanzmusik
on 2009-10-11 14:21:48
wow, just great.
The only improvement i mean is to modify the code by adding or removing some letters before use. If you do not modify, then everyone else can reveal your primary key structure.
Kevin
on 2009-10-09 13:07:54
@ BnoL: This is not intended for security. Pure usability. If you want security you should probably use a lookup table or use UUIDS for records directly.
BnoL
on 2009-09-17 19:22:24
Hi, nice tut.
But I think every encode script need to have a \&
quot;password key\&
quot; so that noone else can decode your ID :) (unless he/she knows your password key).
Topbit
on 2009-07-30 20:46:18
If you only want to use a-z &
amp; 0-9 (base 36), base_convert() will convert both ways easily and quickly.
$number = 999999;
$string = base_convert($number, $frombase = 10, 36);
$num = base_convert($string, $frombase = 36, 10);
if ($num == $number) echo \&
quot;Match!!\\n\&
quot;;
There is also a number of other functions there that will do larger number bases - such as 62, using similar techniques as the above post.
Marcelo
on 2009-07-11 16:02:06
Very useful. Thanks!
Kevin
on 2009-06-18 15:08:42
@ Gerrit: very interesting, thanks for the heads-up!
Gerrit
on 2009-06-18 12:42:39
Great post: I got inspired and changed your code a bit to improve for speed by using int rather than float. This also fixes the rounding problems: try
var_dump(alphaID(alphaID(238328), true) == 238328);
in your converter.
Follow my link for my version of the converter.
devnic
on 2009-06-12 18:43:21
Cool. The best part is that it is a small code that can make the url look more readable and pro.
Đỗ Nam Khánh
on 2009-06-11 17:27:08
Thanks for nice post ^^