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

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

    Object-oriented version of the most up-voted solution

    I've created an object-oriented solution based on Scott's answer:

    setAlphabet($alphabet);
            } else {
                $this->setAlphabet(
                      implode(range('a', 'z'))
                    . implode(range('A', 'Z'))
                    . implode(range(0, 9))
                );
            }
        }
    
        /**
         * @param string $alphabet
         */
        public function setAlphabet($alphabet)
        {
            $this->alphabet = $alphabet;
            $this->alphabetLength = strlen($alphabet);
        }
    
        /**
         * @param int $length
         * @return string
         */
        public function generate($length)
        {
            $token = '';
    
            for ($i = 0; $i < $length; $i++) {
                $randomKey = $this->getRandomInteger(0, $this->alphabetLength);
                $token .= $this->alphabet[$randomKey];
            }
    
            return $token;
        }
    
        /**
         * @param int $min
         * @param int $max
         * @return int
         */
        protected function getRandomInteger($min, $max)
        {
            $range = ($max - $min);
    
            if ($range < 0) {
                // Not so random...
                return $min;
            }
    
            $log = log($range, 2);
    
            // Length in bytes.
            $bytes = (int) ($log / 8) + 1;
    
            // Length in bits.
            $bits = (int) $log + 1;
    
            // Set all lower bits to 1.
            $filter = (int) (1 << $bits) - 1;
    
            do {
                $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
    
                // Discard irrelevant bits.
                $rnd = $rnd & $filter;
    
            } while ($rnd >= $range);
    
            return ($min + $rnd);
        }
    }
    

    Usage

    generate($tokenLength);
    

    Custom alphabet

    You can use custom alphabet if required. Just pass a string with supported chars to the constructor or setter:

    setAlphabet($customAlphabet);
    

    Here's the output samples

    SRniGU2sRQb2K1ylXKnWwZr4HrtdRgrM
    q1sRUjNq1K9rG905aneFzyD5IcqD4dlC
    I0euIWffrURLKCCJZ5PQFcNUCto6cQfD
    AKwPJMEM5ytgJyJyGqoD5FQwxv82YvMr
    duoRF6gAawNOEQRICnOUNYmStWmOpEgS
    sdHUkEn4565AJoTtkc8EqJ6cC4MLEHUx
    eVywMdYXczuZmHaJ50nIVQjOidEVkVna
    baJGt7cdLDbIxMctLsEBWgAw5BByP5V0
    iqT0B2obq3oerbeXkDVLjZrrLheW4d8f
    OUQYCny6tj2TYDlTuu1KsnUyaLkeObwa
    

    I hope it will help someone. Cheers!

提交回复
热议问题