Forum Moderators: coopster

Message Too Old, No Replies

Need help with Random Numbers

         

blaketar

1:19 am on Feb 23, 2006 (gmt 0)

10+ Year Member



I am currently using the following code snippet to generate a random number for picture uploads. This is then used for the picture name when it is uploaded and stored on the server:

$UNIQUENUM = strval(rand(10000000, 44444444));

My question is, lets say after several million uploads is their a chance that the same number could be generated, creating a duplicate named picture on the server or worse, overwriting a photo?

garyr_h

5:39 am on Feb 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Of course there is a possibility. When generating random numbers you could always get duplicates.

If you are that worried, perhaps try putting the numbers in a database, then use an if else statement and check if the number is in use before applying it to the image. And of course if it is, generate another number.

DrDoc

6:11 am on Feb 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Why not just use the unix timestamp as the image name?

Chris_R

6:24 am on Feb 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



or do two columns in excel

>>>first column:
1
2
3
4

or

00001
00002
00003

whatever

Use the little square autocomplete thing dragging the lower right hand corner and make it fill in all 65536 possibilities

>>>second column

(RAND) or whatever it is from excel - select insert formula or whatever and it will be in there

drag and drop so the whole column is filled

then select both columns and sort by the rand number column

now you have a list of 65000 random numbers all with no repeats.

You can do numbers higher than 65000 - just start that way - and you can increment anyway you want.

I use sort by rand all the time.

very useful.

However - if you know how to use databases - that way might be better - I guess my way is technically a databse.

henry0

12:37 pm on Feb 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'll go a bit further in rand
add more rand option like in my example
you could add a line for signs and increase 6 to 10

then I will as per gary_h suggestion indeed use a DB and a query

<<<
for($i = 0; $i < 6; $i++) {

$type[1] = "a¦b¦c¦d¦e¦f¦g¦h¦i¦j¦k¦l¦m¦n¦p¦q¦r¦s¦t¦u¦v¦x¦w¦y¦z";
$type[2] = "1¦2¦3¦4¦5¦6¦7¦8¦9";

$randType = rand(1, 2);

$type = explode("¦", $type[$randType]);

$max = count($type);

// Rand result
$randChar = rand(0, $max);
$rand .= $type[$randChar];
}

>>>

neonpie

5:05 pm on Feb 23, 2006 (gmt 0)

10+ Year Member



i agree with DrDoc - using a time stamp - so unless we go back in time you will never get a repeated number