Is it possible to scale the following functions taken from https://stackoverflow.com/a/9848014/2704706 to encode/decode numbers into an 11 character string?
function lfsr($x) {
return ($x >> 1) ^ (($x&1) ? 0xe10000 : 0);
}
function to_4($x) {
for($i=0;$i<24;$i++)
$x = lfsr($x);
$str = pack("CCC", $x >> 16, ($x >> 8) & 0xff, $x & 0xff);
return base64_encode($str);
}
function rev_lfsr($x) {
$bit = $x & 0x800000;
$x = $x ^ ($bit ? 0xe10000 : 0);
return ($x << 1) + ($bit ? 1 : 0);
}
function from_4($str) {
$str = base64_decode($str);
$x = unpack("C*", $str);
$x = $x[1]*65536 + $x[2] * 256 + $x[3];
for($i=0;$i<24;$i++)
$x = rev_lfsr($x);
return $x;
}
for($i=0; $i<256; $i++) {
$enc = to_4($i);
echo $enc . " " . from_4($enc) . "\n";
}
My end goal would be to use these methods to form URLs with encoded IDs in a similar fashion to the video IDs included in the v $_GET variable in YouTube's URLs, i.e. RArlg6HeZZM in http://www.youtube.com/watch?v=RArlg6HeZZM.
Thanks ahead of time.
I don't know what youtube is doing, but I would do this: randomly generate a string of a fixed length, attempt to insert it into a table where its the primary key, and if you get a primary key exception error, generate a new string and try to insert again. Keep doing that until you finally get a successful insertion (i.e. a random string that is not in the table already). I actually do use this in one app.
Edit:--
Or you can add this as a unique field rather than the primary key:
Then you can still have an auto_increment number as primary key.