note 56246 added to function.rand

From: Date: Sun, 28 Aug 2005 17:15:04 +0000
Subject: note 56246 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-94302@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+56246 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56246&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56246&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56246&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56246&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56246&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56246&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+56246&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#94302) next »