0

I am using the following PHP to generate a few (usually 3) random strings and place them in session variables to use as controls.

function session_var($type) {
if ( !isset ( $_SESSION[$type] ) ) {
$_SESSION[$type] = rand_string( 5 );
}
}

function rand_string( $length ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";    
$size = strlen( $chars );
$str = '';
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return ($str);
}

How do I eliminate the rare occasion where the same random string might be generated more than once in the same session? I don’t want any of the session variables to be the same.

Thanks

martin
  • 393
  • 1
  • 6
  • 21
  • Use `uniqid()` instead of generating your own... http://php.net/manual/en/function.uniqid.php (assuming having numerals in there isn't a problem) – Michael Berkowski Feb 08 '12 at 17:25
  • The lazy and rubbish approach is to `in_array()` and generate the string again if it is duplicated, but I'm sure someone has a better approach than that so this is not going to be an answer. – DaveRandom Feb 08 '12 at 17:26
  • possible duplicate of [PHP: How to generate a random, unique, alphanumeric string?](http://stackoverflow.com/questions/1846202/php-how-to-generate-a-random-unique-alphanumeric-string) – Michael Berkowski Feb 08 '12 at 17:26

2 Answers2

1

I think you should simply rely on a good algorithm for random identifiers generation (especially if you expect the number of such session variables to grow with time and so you need a scalable solution); there are UUID generation algorithm that are guaranteed to have a barely appreciable probability to generate the same uuid twice in the entire lifetime of the solar system.

Try to have a glance on this: http://pecl.php.net/package/uuid

Theory about UUIDs: http://en.wikipedia.org/wiki/Uuid#Version_4_.28random.29

Aldo Stracquadanio
  • 6,167
  • 1
  • 23
  • 34
0

How about something really simple like:

$rand = microtime(true).rand()?

periklis
  • 10,102
  • 6
  • 60
  • 68