Generating (pseudo)random alpha-numeric strings

2019-01-03 13:27发布

How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?

标签: php random
15条回答
相关推荐>>
2楼-- · 2019-01-03 13:28

1 line:

$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;
查看更多
我命由我不由天
3楼-- · 2019-01-03 13:33

Maybe I missed something here, but here's a way using the uniqid() function.

查看更多
放荡不羁爱自由
4楼-- · 2019-01-03 13:33

You can use the following code, copied from this article. It is similar to existing functions except that you can force special character count:

function random_string()
{
    // 8 characters: 7 lower-case alphabets and 1 digit
    $character_set_array = array();
    $character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
    $character_set_array[] = array('count' => 1, 'characters' => '0123456789');
    $temp_array = array();
    foreach ($character_set_array as $character_set) {
        for ($i = 0; $i < $character_set['count']; $i++) {
            $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
        }
    }
    shuffle($temp_array);
    return implode('', $temp_array);
}
查看更多
混吃等死
5楼-- · 2019-01-03 13:33

The modern way to do that with type hint / rand_int for real randomeness

function random_string(int $size): string
{
    $characters = array_merge(
        range(0, 9),
        range('A', 'Z')
    );

    $string = '';
    $max = count($characters) - 1;
    for ($i = 0; $i < $size; $i++) {
        $string .= $characters[random_int(0, $max)];
    }

    return $string;
}
查看更多
混吃等死
6楼-- · 2019-01-03 13:34

If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:

substr( sha1( time() ), 0, 15 )

time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.

查看更多
Explosion°爆炸
7楼-- · 2019-01-03 13:40
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo generateRandomString();
查看更多
登录 后发表回答