2017-12-02 7 views
0

アルファベット数字とし、それをデコードしてエンコードできるようにします。 例:php IDのエンコード/デコード方法USER(int)アルファ数値形式の9桁の数字

$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 
} 
+0

あなたはそれを働かせましたか? – musashii

答えて

-1

あなたは機能の下に使用することができます。一般的には

<?php 
echo base64_encode(123); //MTIz 
echo "<br>"; 
echo base64_decode(base64_encode(123)); //123 
?> 
+0

'base64_encode'はアルファベットの文字ではありません:' base64_encode( '1')=== 'MQ ==' ' –

0

そのユーザーIDを生成するPHPの関数uniqid()を使用するには良いアイデア。戻り値もurl-validです。

0

私はそれで遊んと、それはあなたがこのようにそれを行うことができますこれらの機能を使用してPHP random string generatorCan a seeded shuffle be reversed?

function generateRandomString($length = 10) { 
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
    $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]]; 
    } 
} 

からのコードを使用して動作するようになった、あなたは$seed

しかし
//$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 
を保存する必要があります
関連する問題