开发者

Random alphanumeric pin?

开发者 https://www.devze.com 2023-02-18 10:44 出处:网络
I\'m working on creating a random 5 character pin for a script. I was wondering if anyone else had a better one?

I'm working on creating a random 5 character pin for a script. I was wondering if anyone else had a better one?

$pin = '';
while($开发者_如何学运维i != 5){
    $string = '23456789abcdefghjkmnprstvwxyzABCDEFGHJKLMNPRSTVWXYZ'; 
    $pos = rand(0,(strlen($string)-1));
    $pin = $pin . $string[$pos];
    $i++;
}

echo $pin;


Just marginally different/shorter. No reason to declare the valid characters every time, and for loop is often considered preferable to while.

$pinlength = 5;
$charSet = '23456789abcdefghjkmnprstvwxyzABCDEFGHJKLMNPRSTVWXYZ'; 
$pin = '';
for($a = 0; $a < $pinlength; $a++) $pin .= $charSet[rand(0, strlen($charSet))];

echo $pin;

Or, just for the hell of it:

$makeCharacterSelect = 
         function ($charSet) {return function use ($charSet) 
                                     {return $charSet[rand(0, strlen($charSet))];};
$pinlength = 5; $c = $makeCharacterSelect('23456789abcdefghjkmnprstvwxyzABCDEFGHJKLMNPRSTVWXYZ');

$pin = '';
for($a = 0; $a < $pinlength; $a++) $pin .= $c();


$pin = substr(uniqid(), 0, 5); // Mind you, this doesn't contain
                               // upper-case letters
0

精彩评论

暂无评论...
验证码 换一张
取 消