A way to generate guaranteed unique random numbers

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

A way to generate guaranteed unique random numbers

Post by aditya2071990 »

This code can definitely generate random numbers that will always be unique, that is, a number once generated will never be generated again. This code will work only till the end of the UNIX epoch, though:

Code: Select all

function getUserIP(){
    
    $userIPActual = $_SERVER['REMOTE_ADDR'];
    global $userIP;
    $userIP = str_replace('.','',$userIPActual);
    return  $userIP;
    
};
 
function getTime(){
    
    $microTimeActual = microtime(true);
    global $microTime;
    $microTime = str_replace('.','',$microTimeActual);
    return  $microTime;
    
};
 
function generateaRandom(){
    
    function generateRandom($input){
            
            $random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int
        
            $random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string
            
            $randomSum = $random_number.$random_string.'adjafhdklf';
            
            $mostRandom = md5($randomSum.$input);
            
            return $mostRandom;
        
        };
    
    function generate_a_random(){
    
        $a_random_string = generateRandom(generateRandom(generateRandom(generateRandom(2071990))));
        
        return $a_random_string;
    
    };
    
    global $final_random;
    $final_random = generate_a_random();
    
    return $final_random;
    
};
 
getUserIP(); getTime(); generateaRandom();
 
$unique_number = $userIP.$microTime.$final_random;
And I almost forgot to mention, some of the code in the generateRandom() function, I took from a user called "deeeeeen alxndr0u", a user who posted the code on the php.net's rand() function page.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: A way to generate guaranteed unique random numbers

Post by onion2k »

1. You're using globals to pass values around. That is very bad practise. Worse still, you're calling variables into the global scope that haven't been defined previously.

2. You're returning values from functions which is good... but the function calls don't store them. So the returned value is just being lost. If you stored the value you could eliminate all the nasty global stuff.

3. You're defining a function within another function. That's unnecessary, and will make maintaining the code much harder.

4. The randomness is dubious at best. I suspect you've actually made something that's really very non-random that just looks random because you've used microtime(). It would need some very rigorous testing before I was willing to trust it.

5. All in all, the code is a mess of spaghetti code that could be refactored into about 10 lines.

6. Most importantly of all, you're duplicating PHP's uniqid() functionality. That will definitely give you a completely unique value that you could append to a user id and a random string to give you something that would be guaranteed to work proper.
User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

Re: A way to generate guaranteed unique random numbers

Post by aditya2071990 »

Thank you for taking time to read my code and comment on it :)

1. I did not know that was bad practise. So you mean I must store variables like this:

Code: Select all

$returnValue = return $functionResult;
3. I was just being lazy, sorry. I just defined functions as-I-went, so the mistake.
4. I am more than willing to subject it to testing. But I don't know how...can you please suggest a way?
5. I am a n00b. I know that doesn't make a good excuse, but I am a n00b to all programming, and most of my time is spent in wrapping my head around on how to solve problems, rather than on how to solve them effectively...
6. I did not know about that. I guess what I can do is simply concatenate the user's IP along with a value from uniqid(), will that work?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: A way to generate guaranteed unique random numbers

Post by onion2k »

1. Yes.
2. ...
3. It's fine to be lazy with your own stuff, but if you're going to release the code to the public you'd do well to polish it first.
4. That isn't something I can help you with.
5. Same as point 3 really. Go over your code and refine is as much as possible before you release it.
6. That would work, sure.
User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

Re: A way to generate guaranteed unique random numbers

Post by aditya2071990 »

Thank you, onion2k, I guess I should post the query on the testing part in the 'testing' forum. And the next time I post here, I will post only if I want to release the code for public use, and I seriously intend to polish it off...

Cheers,
Aditya.
User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

Re: A way to generate guaranteed unique random numbers

Post by aditya2071990 »

Okay, now here's another piece, based on suggestions. Do let me know what you guys think:

Code: Select all

function getTime(){
    
    $microTimeActual = microtime(true);
    global $microTime;
    $microTime = str_replace('.','',$microTimeActual);
    return  $microTime;
    
};
 
getTime();
 
$uniq = uniqid($microTime,true);
 
function getUserIP(){
    
    $userIPActual = $_SERVER['REMOTE_ADDR'];
    global $userIP;
    $userIP = str_replace('.','',$userIPActual);
    return  $userIP;
    
};
 
getUserIP();
 
$uniqueId = $uniq.$userIP;
 
$uniqueId = str_replace('.','',$uniqueId);
 
echo $uniqueId;
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: A way to generate guaranteed unique random numbers

Post by onion2k »

Your code does the same as...

Code: Select all

$time = microtime(true);
$unique_id = uniqid($time,true);
$unique_id = str_replace(".","",$unique_id.$_SERVER['REMOTE_ADDR']);
echo $unique_id;
 
Or, if you don't want to write it out long hand...

Code: Select all

echo str_replace(".","",uniqid(microtime(true),true).$_SERVER['REMOTE_ADDR']);
Seriously, you don't need all these globals. If you're going to rewrite it try to take them out.
User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

Re: A way to generate guaranteed unique random numbers

Post by aditya2071990 »

Oh my god, 29 lines condensed into ONE LINE?

That was one hell of a display of awesomeness :bow:

And I forgot to remove the globals...that was a mistake yeah...

Onion, if u don't mind me asking how old r u ?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: A way to generate guaranteed unique random numbers

Post by onion2k »

aditya2071990 wrote:Onion, if u don't mind me asking how old r u ?
I'm 31.
User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

Re: A way to generate guaranteed unique random numbers

Post by aditya2071990 »

Oh...I thought you were older, with a cart load of experience behind you....but that was great, indeed...
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: A way to generate guaranteed unique random numbers

Post by Eran »

31 is pretty old :P
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: A way to generate guaranteed unique random numbers

Post by onion2k »

pytrin wrote:31 is pretty old :P
:(
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: A way to generate guaranteed unique random numbers

Post by Eran »

:wink: I'm not far behind...
User avatar
dyrathror
Forum Newbie
Posts: 6
Joined: Thu Oct 02, 2008 5:30 am

Re: A way to generate guaranteed unique random numbers

Post by dyrathror »

Hi,

according to the theory it is not possible to generate completey random numbers alone with a computer program. Specially not:
a number once generated will never be generated again
The problem is seperated in finding a unique starting number to generate the series for the random number which can be solved only with special hardware and finding an algorithm which has no loop which is not found until now as long as I know.

Practically we take the rand() function from UNIX which is proven to have a very long loop ;)

D.
User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

Re: A way to generate guaranteed unique random numbers

Post by aditya2071990 »

dyrathror wrote:Hi,

according to the theory it is not possible to generate completey random numbers alone with a computer program.
Hmmm, but that's why we are adding the microseconds and user IP addresses together. Theory also says that no two computers can have the same IP address at the same microsecond...;)

But I am open to know more. I would definitely like to add yet another layer of randomness to what is already present, so any suggestions in that direction are most welcome...
Post Reply