note 111376 added to function.srand

From: Date: Wed, 13 Feb 2013 21:40:09 +0000
Subject: note 111376 added to function.srand
Groups: php.notes 
Request: Send a blank email to php-notes+get-193625@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 69.147.83.199 Probable Submitter: 187.152.98.104 ---- Manual Page -- http://php.net/manual/en/function.srand.php Edit -- https://master.php.net/note/edit/111376 Del: integrated -- https://master.php.net/note/delete/111376/integrated Del: useless -- https://master.php.net/note/delete/111376/useless Del: bad code -- https://master.php.net/note/delete/111376/bad+code Del: spam -- https://master.php.net/note/delete/111376/spam Del: non-english -- https://master.php.net/note/delete/111376/non-english Del: in docs -- https://master.php.net/note/delete/111376/in+docs Del: other reasons-- https://master.php.net/note/delete/111376 Reject -- https://master.php.net/note/reject/111376 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#193625) next »