Reputation: 2904
I'm using the PHP function uniqid() on my server. It should be something like a microtime. So I think it is unique FOR ONE server. Is it correct?
How can I get a unique id if I scale my server with a loadbalancer? I need a string with less than 31 characters.
Thanks
Upvotes: 3
Views: 1388
Reputation: 24261
I would suggest combining multiple sources of entropy. This way you wouldn't rely on some assumptions (local IP address being different) or luck (two servers won't do the same thing exactly at the same nanotime).
Things that come to my mind (and are pretty portable, not platform specific):
After all you can use this as an input to some hash function, just to normalize to 30-byte string (e.g. last 30 bytes of md5sum of concatenation of strval()
of input values).
Upvotes: 2
Reputation: 41050
You can use uniqid()
with a different prefix for each server passed as first argument. Check the documentation.
string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )
prefix
Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.
With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.
Example:
$serverId = str_replace('.', '', $_SERVER["SERVER_ADDR"].$_SERVER["SERVER_PORT"]);
$uid = substr(uniqid($serverId, true), 0, 30);
Or check out this great uuid() function: http://cakebaker.42dh.com/wp-content/uploads/2007/01/uuid_component_2007-01-24.zip
Upvotes: 2
Reputation: 83622
Try
$uid = uniqid($serverId, true);
This will prefix every $uid
with the $serverId
.
Upvotes: -1
Reputation: 4896
Yes, as its manual page says, it's based on the current time in microseconds.
You can use the prefix
argument to pass in a host-specific prefix.
Even with the more_entropy
argument you have 7 characters left for the prefix, allowing for 256**7 hosts.
Upvotes: 1
Reputation: 11556
You should set the prefix to a unique string (unique for each server is your system). Examples could be hostname or IP address. Keep this to less than 17 characters (or 7 if you use additional entropy).
Upvotes: 0