Page 1 of 1

How to generate a unique random number in php???

Posted: Thu Feb 03, 2011 1:21 am
by hmdnawaz
How to generate a unique random number in php??? Any one who can help me?

Re: How to generate a unique random number in php???

Posted: Thu Feb 03, 2011 2:26 am
by Peter Kelly
Well a simple way would be to use

Code: Select all

<?php
$random = rand();
?>
This will generate random numbers but i'm sure the people with the know how will tell you not to use it. But for simple use i'd just use that.

Re: How to generate a unique random number in php???

Posted: Thu Feb 03, 2011 2:27 am
by tutigan
You can use the rand function, although that will create a totally random number... http://php.net/manual/en/function.rand.php
to have a unique number, you can use the PHP session id, but for that to work multiple times for the same person... I don't know about that one :?
to use the session id, you can just use:

Code: Select all

session_start();
$sessionID = session_id();

Re: How to generate a unique random number in php???

Posted: Thu Feb 03, 2011 2:39 am
by Peter Kelly
Thinking about it you could try using the function uniqid(); (http://uk3.php.net/manual/en/function.uniqid.php)

Re: How to generate a unique random number in php???

Posted: Thu Feb 03, 2011 6:03 am
by Zyxist
What uniqueness do you want? If you want to get several numbers, and ensure the calculated random values do not repeat, you must put rand() into a loop:

Code: Select all

do
{
   $random = rand();
}
while(in_array($random, $randomValues));
$randomValues[] = $random;
Without such checking, the randomization functions must have some extra mathematical properties.

Re: How to generate a unique random number in php???

Posted: Thu Feb 03, 2011 8:42 am
by Apollo
Instead of using the rand() function I recommend using the mt_rand() function. It produces better random (better as in longer period, less correlation between bits, etc, and it's also faster).

If you really want to make sure it's unique, combine it with a (micro-)timestamp, for example:

Code: Select all

$uniqueRandomNumber = implode('',array_map('hexdec',explode(',',wordwrap(md5(microtime(false)),8,',',true)))).mt_rand();

Re: How to generate a unique random number in php???

Posted: Thu Feb 03, 2011 9:44 am
by John Cartwright
In a linux environment, it is always recommended to use urandom, i.e.,

Code: Select all

if ($fp = @fopen('/dev/urandom','rb') !== false) {
    $random = fread($fp,16);
    fclose($fp);
}
Otherwise, +1 for mt_rand() + seeding