PHP random string generator more random than expected

I used this for a gender random 12 character string:

//  lost-in-code.com/programming/php-code/php-random-string-with-numbers-and-letters
$ch = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$%^&(){}[]+=-_/?|*#";
$sc = "";    
for ($p = 0; $p < 12; $p++) {
    $sc .= $ch[mt_rand(0,82)];  // 83 is the strlen of characters
} 

It turns out that in practice it may contain a space in the line. This is not expected!

Why? Does this underline look like space? This caused random (and still unmanageable) errors.

Thank.

+3
source share
4 answers

When guessing (not tested), changing quotes around the string $ ch to single quotes. stops braces from "rating"


Edit:

Just update after some testing - it does NOT convert "as is" - so there is something else in the code causing the problems. Just ran it over 100,000 times without spaces.

- , ( , ), .

+3

. , , . , "M0i/ %20 = 3ia5" urldecode "M0i/= 3ia5".

+1

You can create html objects. Imagine if your code is generated  or  , for example, a space appears in the line.

+1
source

Why not just use:

    $length = 12;
    $randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
    echo $randomString;
+1
source

All Articles