note 32982 modified in function.rand by pollita

From: Date: Fri, 13 Jun 2003 04:09:52 +0000
Subject: note 32982 modified in function.rand by pollita
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-50262@lists.php.net to get a copy of this message
[ Editor's Note: The string which this function ultimately creates may and probably will repeat given sufficient itterations even though the seed value is based on the time which is a sequentially increasing number. uniqid() provides greater randomness with a certainty of no repeats. ] If you want a REALLY random string, here's how you do it: function randStr( $length ) { if ( $length > 36 ) { return "ERROR"; } else { $str = md5(mktime()); $cutoff = 31 - $length; $start = rand(0, $cutoff); return substr($str, $start, $length); } } Not only does it first generate a number that will never repeat, but it then MD5s it for flavour, then it chops it down to whatever length you want (up to 36 characters). However, if you do not use the full 36, it will chop it from a random place in the string, ie: e5hdksuth834h5hfcb6j4la43gj7e0p234b6 is generated... if you specify 5 chars, it wont just use: e5hdk or 234b6 (first / last 5 chars of the string), but it will use a string of 5 chars from any randomly selected location (within the necessary scope) within the string! Pretty nifty, eh'? -my 2¢ --was-- If you want a REALLY random string, here's how you do it: function randStr( $length ) { if ( $length > 36 ) { return "ERROR"; } else { $str = md5(mktime()); $cutoff = 31 - $length; $start = rand(0, $cutoff); return substr($str, $start, $length); } } Not only does it first generate a number that will never repeat, but it then MD5s it for flavour, then it chops it down to whatever length you want (up to 36 characters). However, if you do not use the full 36, it will chop it from a random place in the string, ie: e5hdksuth834h5hfcb6j4la43gj7e0p234b6 is generated... if you specify 5 chars, it wont just use: e5hdk or 234b6 (first / last 5 chars of the string), but it will use a string of 5 chars from any randomly selected location (within the necessary scope) within the string! Pretty nifty, eh'? -my 2¢ http://www.php.net/manual/en/function.rand.php

« previous php.notes (#50262) next »