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

后端 未结 28 2215
隐瞒了意图╮
隐瞒了意图╮ 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 22:57

    A simple solution is to convert base 64 to alphanumeric by discarding the non-alphanumeric characters.

    This one uses random_bytes() for a cryptographically secure result.

    function random_alphanumeric(int $length): string
    {
        $result='';
        do
        {
            //Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
            $bytes=random_bytes(($length+3-strlen($result))*2);
            //Discard non-alhpanumeric characters
            $result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
            //Keep adding characters until the string is long enough
            //Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
        }while(strlen($result)<$length+3);
        return substr($result,0,$length);
    }
    

提交回复
热议问题