PHP Function Code for Random Number + Character Generator

View QuestionsCategory: CodePHP Function Code for Random Number + Character Generator
admin Staff asked 7 years ago

Need a function that creates a random string with length of $length with characters 0-9a-zA-Z, first digit will not be a number.

1 Answers
Best Answer
admin Staff answered 7 years ago
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<pre>
    function getRandomAndUniqueToken($length) {
        $token = "";
        $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $codeAlphabet .= "abcdefghijklmnopqrstuvwxyz";
        $max = strlen($codeAlphabet); // edited
        for ($i = 0; $i &lt; $length; $i++) {
            if ($i == 1) {
                $codeAlphabet .= &quot;0123456789&quot;;
                $max = strlen($codeAlphabet);
            }
      $token .= $codeAlphabet[rand(0, $max - 1)];
        }
        return $token;
    }
</pre>