开发者

Generating a unique random string of a certain length and restrictions in PHP?

I have the need to generate a random alphanumeric string of 8 characters. So it should look sort of like b53m1isM for example. Both upper and lower case, letters and numbers.

I already have a loop that runs eight times and what I want it to do is to concatenate a string with a new random character every iteration.

Here's the loop:

$i = 0;
    while($i < 8)
    {
        $randPass = $randPass + //rand开发者_高级运维om char
        $i = $i + 1;
    }

Any help?


function getRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';

    for ($i = 0; $i < $length; $i++) {
        $string .= $characters[mt_rand(0, strlen($characters) - 1)];
    }

    return $string;
}


function randr($j = 8){
    $string = "";
    for($i=0; $i < $j; $i++){
        $x = mt_rand(0, 2);
        switch($x){
            case 0: $string.= chr(mt_rand(97,122));break;
            case 1: $string.= chr(mt_rand(65,90));break;
            case 2: $string.= chr(mt_rand(48,57));break;
        }
    }
    return $string; 
}

echo randr(); // b53m1isM


$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Output: m-swm3AP8X50VG4jCi.jpg
echo 'm-'.substr(str_shuffle($permitted_chars), 0, 16).'.jpg';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜