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
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.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).You can use
uniqid()
with a different prefix for each server passed as first argument. Check the documentation.Example:
Or check out this great uuid() function: http://cakebaker.42dh.com/wp-content/uploads/2007/01/uuid_component_2007-01-24.zip
Try
This will prefix every
$uid
with the$serverId
.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).