How to generate a unique random number in php???
Moderator: General Moderators
How to generate a unique random number in php???
How to generate a unique random number in php??? Any one who can help me?
-
Peter Kelly
- Forum Contributor
- Posts: 143
- Joined: Fri Jan 14, 2011 5:33 pm
- Location: England
- Contact:
Re: How to generate a unique random number in php???
Well a simple way would be to use
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.
Code: Select all
<?php
$random = rand();
?>Re: How to generate a unique random number in php???
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:
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();-
Peter Kelly
- Forum Contributor
- Posts: 143
- Joined: Fri Jan 14, 2011 5:33 pm
- Location: England
- Contact:
Re: How to generate a unique random number in php???
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???
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:
Without such checking, the randomization functions must have some extra mathematical properties.
Code: Select all
do
{
$random = rand();
}
while(in_array($random, $randomValues));
$randomValues[] = $random;
Re: How to generate a unique random number in php???
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:
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();- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: How to generate a unique random number in php???
In a linux environment, it is always recommended to use urandom, i.e.,
Otherwise, +1 for mt_rand() + seeding
Code: Select all
if ($fp = @fopen('/dev/urandom','rb') !== false) {
$random = fread($fp,16);
fclose($fp);
}