note 111376 deleted from function.srand by googleguy

From: Date: Wed, 13 Feb 2013 21:45:54 +0000
Subject: note 111376 deleted from function.srand by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-193626@lists.php.net to get a copy of this message
Note Submitter: luis at portanel dot com ---- This is my (ugly) one-liner to generate random strings of any given length: <?php for($r=rand(48,109),srand(date('s'));$i<$LENGTH;$i++,$r=rand(48,109)) echo chr($r>83?$r+13:($r>57?$r+7:$r)); /* This will output something like: Kdf43l1Z // With $LENGTH=8; */ ?> If you want to see how this works, here it's the expanded version: <?php function RandomString($LENGTH) { $s=''; srand(date('s')); for($i=0;$i<$LENGTH;$i++) { $r=rand(0,61); // Random number for each of our 62 possible characters // Lower case char if($r>=36) $IndexASCII = $r+61; // $r+61 is between 97 and 122, which are the ASCII indexes of lower case letters // Upper case char elseif($r>=10) $IndexASCII = $r+55; // $r+55 is between 65 and 90, which are the ASCII indexes of UPPER CASE letters // Number else $IndexASCII = $r+48; // $r+48 is between 48 and 58, which are the ASCII indexes of the numbers // Just add the character to our string $s.=chr($IndexASCII); } return $s; } ?>

« previous php.notes (#193626) next »