Yesterday I came across this short article on dev.to which advised against using timestamps as unique IDs in file names when handling file uploads. The author instead recommended using a random string generator like the Str::random()
in Laravel which he highlighted by using 8 character long random string.
There are two problems with this approach/advice/thinking.
- Timestamps are not just used for unique IDs in such cases but also to future proof names to avoid collisions.
- There is no such thing as true random data as far as generic algorithms are concerned. They all follow a set pattern and collisions are possible.
So in this case it’s ok if you are making a small project which isn’t going to see many instances of random string generation. But if you are not working on such a project then it might be a good idea to think a bit and not do this random string thing.
It’s unlikely an experienced developer would use a regular timestamp, such as one given by time()
, multiple times in same execution cycle in such a case since code executes in nanoseconds & milliseconds. So using time()
is likely to generate duplicate values in the same execution cycle (which is what the author highlighted in the aforementioned article).
One of the ways to go about this is to use microtime()
or hrtime()
which provides current time in microseconds and so its not going provide a duplicate value in same execution cycle even when used on consecutive lines of code. So to get a unique string, one of the ideal ways is to do this:
$timestamp_as_number = hrtime( true );
// convert numbers to alpha-numeric string
$unique_string = base_convert( $timestamp_as_number, 10, 36 );
This way provides a collision proof and future proof unique string – much better than using a randomly generated string.
इसीलिए अपन SELECT MAX(col) + 1 FROM table
करते हैं।
थोड़ा टाइम ज़्यादा लगता है तो क्या हुआ
और थोड़े बहुत DUPREC तो चलते हैं न
/s