note 55013 deleted from function.mt-rand by cmb

From: Date: Sun, 19 Jan 2020 08:34:05 +0000
Subject: note 55013 deleted from function.mt-rand by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-213908@lists.php.net to get a copy of this message
Note Submitter: sean at codeaholics dot com ---- You really shouldn't generate a number to determine the _type_ of the char, then the char itself. If security is an issue for you, and you want to maintain as much entropy as possible, you should use a function similar to the one below. Since this seems to be getting repeated over-and-over, I explained (beat into the ground?) the issue on http://www.codeaholics.com/randomCode.php The code: <?php //// // Returns a random code of the specified length, containing characters that are // equally likely to be any of the digits, uppercase letters, or lowercase letters. // // The default length of 10 provides 839299365868340224 (62^10) possible codes. // // NOTE: Do not call wt_srand(). It is handled automatically in PHP 4.2.0 and above // and any additional calls are likely to DECREASE the randomness. //// function randomCode($length=10){ $retVal = ""; while(strlen($retVal) < $length){ $nextChar = mt_rand(0, 61); // 10 digits + 26 uppercase + 26 lowercase = 62 chars if(($nextChar >=10) && ($nextChar < 36)){ // uppercase letters $nextChar -= 10; // bases the number at 0 instead of 10 $nextChar = chr($nextChar + 65); // ord('A') == 65 } else if($nextChar >= 36){ // lowercase letters $nextChar -= 36; // bases the number at 0 instead of 36 $nextChar = chr($nextChar + 97); // ord('a') == 97 } else { // 0-9 $nextChar = chr($nextChar + 48); // ord('0') == 48 } $retVal .= $nextChar; } return $retVal; } ?>

« previous php.notes (#213908) next »