0

I want it to be alpha numeric and where I can decode it and encode it. Example:

$id = 12452;
$encoded = encode_id( $id ); // return -> R51RT74UJ
$decoded = decode_id( $encoded ); // return -> 12452
function encode_id( $id, $length = 9) {
    return $id; // With a maximum of 9 lengths
}

function decode_id( $id, $length = 9) {
    return $id; // With a maximum of 9 lengths
}
Clary
  • 544
  • 1
  • 7
  • 8

3 Answers3

1

You can use below function:

<?php
 echo base64_encode(123);  //MTIz
 echo "<br>";
 echo base64_decode(base64_encode(123)); //123
?>
slon
  • 1,002
  • 1
  • 8
  • 12
0

in general its a better idea to use php's function uniqid() to generate user id's. the return value is also url-valid.

netzding
  • 772
  • 4
  • 21
0

I played around with it and got it to work by using code from PHP random string generator and Can a seeded shuffle be reversed?

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function seeded_shuffle(array &$items, $seed = false) {
    $items = array_values($items);
    mt_srand($seed ? $seed : time());
    for ($i = count($items) - 1; $i > 0; $i--) {
        $j = mt_rand(0, $i);
        list($items[$i], $items[$j]) = array($items[$j], $items[$i]);
    }
}

function seeded_unshuffle(array &$items, $seed) {
    $items = array_values($items);

    mt_srand($seed);
    $indices = [];
    for ($i = count($items) - 1; $i > 0; $i--) {
        $indices[$i] = mt_rand(0, $i);
    }

    foreach (array_reverse($indices, true) as $i => $j) {
        list($items[$i], $items[$j]) = [$items[$j], $items[$i]];
    }
}

using those functions you can do it like this, you need to save the $seed though

//$length is the expected lentgth of the encoded id
function encode_id( $id, $seed, $length = 9) {
    $string = $id . generateRandomString($length - strlen($id));
    $arr = (str_split($string));
    seeded_shuffle($arr, $seed);
    return implode("",$arr);    
}

//$length is the expected lentgth of the original id
function decode_id( $encoded_id, $seed, $length = 6) {
   $arr = str_split($encoded_id);
   seeded_unshuffle( $arr, $seed);
   return substr(implode("", $arr),0,$length);
}

$id =  "123456";
$seed = time();
$encodedId =  encode_id($id,$seed);
echo decode_id($encodedId,$seed); //outputs 123456
musashii
  • 445
  • 6
  • 13