Reputation: 387
I'm using a process to put a name on user profile images and i'm afraid of collisions. The name pattern that i'm using is the following:
9999999_9999999_9999999
So the images are named like:
4533381_1284948_8023255.jpg
The range to the integer is from 1.000.000 to 9.999.999 Is necessary to check if a image with the same name already exists on user profile images directory? (assuming that all the images resides on the same directory level).
The integers are generated using the php function mt_rand(1000000,9999999);
Upvotes: 1
Views: 44
Reputation: 27565
Probability of a collision is very low in your case (though possible).
Counting all possible values of image name: (9999999-1000000+1)^3 == 7.29 * 10^20
.
Hint: you may increase this value by generating numbers between 0
and 9999999
and left-padding them with zeros while converting to strings, e.g.: sprintf("%07d", $number)
mt_rand
is a relatively good random generator.
A collision will probably never happen.
However, if it's easy in your app's context, you may implement the check that the name is unoccupied, and if it's not, just re-generate random name in the same way.
A kind of do { $name = generate_name(); } while(is_occupied($name));
loop.
Note that this solution is safer than deterministic hashing proposed in comments.
The reason is that hash collisions are possible as well, and if it happens, then you're done — it's deterministic and you have no possibility to generate another random.
Or you have to use a chain of hash functions for the case of collisions. This means a similar do-while loop, but slightly more complex, involving data which the hash is calculated on and a counter (which affects hash calculation). More code with no benefits, IMO.
Upvotes: 1
Reputation: 759
Simple answer: No.
Long answer: Even with a 32 digit random string of numbers and letters, you will eventually possibly hit a collision. As someone commented, you should try to use something related to the user, such as their user ID, and hash it using some form of hasher.
See here for hashing in PHP.
Upvotes: 0