PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

后端 未结 28 2815
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 22:20

How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends y

28条回答
  •  清歌不尽
    2020-11-21 23:19

    after reading previous examples I came up with this:

    protected static $nonce_length = 32;
    
    public static function getNonce()
    {
        $chars = array();
        for ($i = 0; $i < 10; $i++)
            $chars = array_merge($chars, range(0, 9), range('A', 'Z'));
        shuffle($chars);
        $start = mt_rand(0, count($chars) - self::$nonce_length);
        return substr(join('', $chars), $start, self::$nonce_length);
    }
    

    I duplicate 10 times the array[0-9,A-Z] and shuffle the elements, after I get a random start point for substr() to be more 'creative' :) you can add [a-z] and other elements to array, duplicate more or less, be more creative than me

提交回复
热议问题