If a hash function such as MD5 can be used instead of encryption, you could try crc32()
instead, which produces shorter (but with much higher chances of collisions) strings.
If you just care about encoding, you could do something simpler:
function encode($id) {
$id_str = (string) $id;
$offset = rand(0, 9);
$encoded = chr(79 + $offset);
for ($i = 0, $len = strlen($id_str); $i < $len; ++$i) {
$encoded .= chr(65 + $id_str[$i] + $offset);
}
return $encoded;
}
function decode($encoded) {
$offset = ord($encoded[0]) - 79;
$encoded = substr($encoded, 1);
for ($i = 0, $len = strlen($encoded); $i < $len; ++$i) {
$encoded[$i] = ord($encoded[$i]) - $offset - 65;
}
return (int) $encoded;
}
Example:
var_dump(encode(50624)); // string(6) "TKFLHJ"
Encryption version:
define('CRYPTO_KEY', 'Secret key');
function encrypt($id) {
return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, CRYPTO_KEY, (string) $id, MCRYPT_MODE_ECB));
}
function decrypt($encrypted) {
return (int) base64_decode(mcrypt_decrypt(MCRYPT_BLOWFISH, CRYPTO_KEY, $encrypted, MCRYPT_MODE_ECB));
}