note 84994 added to function.rand

From: Date: Fri, 08 Aug 2008 22:31:10 +0000
Subject: note 84994 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-143317@lists.php.net to get a copy of this message
Random password generation isn't probably something we link with processing speed I created 3 functions (all 3 were tested with both mt_rand() and rand()) the first sets all the characters in a string ie $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; then uses a for loop (for use with dynamic password length) to run through using substr to create the "random password" The second function does the same but instead of using substr, it uses this syntax $str{$rand} to get the random character the third function used char(). 3 rands were needed for this, one for numeric, one for lowercase and one for uppercase and then another rand used to pick which of those 3 to use I performed 1,000,000 tests on each function and then took the average execution time of each function function 2 was over 2 times faster than function 3 function 2 was also just over 0.5 times faster than function one So for the fastest way to generate a random password is to use the $str{} syntax here is the function that did 1,000,000 passwords each of which were 50 characters in length in 0.00063 seconds per function execution function pass_gen($pass_length) { $str = '012345679abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $pass = ''; $str_len = strlen($str) -1; for($i=0; $i < $pass_length; $i++) { $rand = mt_rand(0, $str_len); $pass .=$str[$rand]; } return $pass; } echo "\n"; echo pass_gen(10); echo "\n"; which outputs : v2vH0SdpZy ---- Server IP: 69.147.83.197 Probable Submitter: 79.76.108.27 ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit -- https://master.php.net/note/edit/84994 Del: integrated -- https://master.php.net/note/delete/84994/integrated Del: useless -- https://master.php.net/note/delete/84994/useless Del: bad code -- https://master.php.net/note/delete/84994/bad+code Del: spam -- https://master.php.net/note/delete/84994/spam Del: non-english -- https://master.php.net/note/delete/84994/non-english Del: in docs -- https://master.php.net/note/delete/84994/in+docs Del: other reasons-- https://master.php.net/note/delete/84994 Reject -- https://master.php.net/note/reject/84994 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#143317) next »