note 56246 deleted from function.rand by felipe

From: Date: Sun, 30 Dec 2007 18:43:56 +0000
Subject: note 56246 deleted from function.rand by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134427@lists.php.net to get a copy of this message
Note Submitter: andy at andycc dot net ---- Need a string of random letters and numbers for a primary key/session ID? Here's a dead simple function that works pretty efficiently. Set $template to a string of letters/numbers to choose from (e.g. any of the letters in this string can be returned as part of the unique ID - could use symbols etc.) Then call GetRandomString(?) with an integer value that defines how long you want the string to be. <?php // Andy Shellam, andy [at] andycc [dot] net // generate a random string of numbers/letters settype($template, "string"); // you could repeat the alphabet to get more randomness $template = "1234567890abcdefghijklmnopqrstuvwxyz"; function GetRandomString($length) { global $template; settype($length, "integer"); settype($rndstring, "string"); settype($a, "integer"); settype($b, "integer"); for ($a = 0; $a <= $length; $a++) { $b = rand(0, strlen($template) - 1); $rndstring .= $template[$b]; } return $rndstring; } echo GetRandomString(30); ?> This is the output after running the script 5 times: i7wwgx8p1x0mdhn6gnyqzcq3dpqsc0 5ntlvapx6o90notob4n7isdp0ohp19 ojnyuile9y459cjr1vf9kgdas4tscw 2fr5dqn62kzfjvywqczjaoyrqjeyfd 9dtnk7e18jjx1og4gr4noznldit0ba The longer and more varied the text of $template, the more random your string will be, and the higher the value of GetRandomString(?), the more unique your string is. Note also, if you pass a non-integer into the function, the settype($length) will force it to be 0, hence you won't get anything returned, so make sure you pass it a valid integer.

« previous php.notes (#134427) next »