1

I was just wondering, in term of security, what about using multiple rand() functions to generate one unique ID?

Like so: $unique_id = rand(1, 15) . rand(15, 50) . rand(50, 100) . rand(15, 50); would result to something like 8215236.

I don't want to use time().

Do you think the risk of collision is high if I use multiple rand while generating unique IDs?

  • Why not use [`openssl_random_pseudo_bytes`](http://php.net/manual/ro/function.openssl-random-pseudo-bytes.php)? It's the closest thing PHP has when it comes to randomness. Or [`uniqid`](http://php.net/manual/ro/function.uniqid.php)? Don't roll your own solution when you have perfectly valid ones out of the box. – Andrei Oct 18 '16 at 13:07
  • To create a unique_id, I always use the SHA-1 hash of the date. – Koen Hollander Oct 18 '16 at 13:09
  • "*I don't want to use `time()`*" why not? You'd be a lot more safeguarded from using a timestamp, as there is a chance that your approach will generate two identical IDs, given enough simulations. – Qirel Oct 18 '16 at 13:13
  • Well yes using time, microtime, uniqueid, md5, sha-1 etc. are the standard methods to generate unique IDs, but I just wanted to create my own simple unique ID generator, simple but effective, and I was wondering if I could use rand()s instead. – David Forestier Oct 18 '16 at 13:18
  • Also, (just a supposition), is there any ways for a hacker to change the way how time() and microtime() generates the values? For exemple by changing server's actual time? – David Forestier Oct 18 '16 at 13:20
  • I don't see the point in reinventing the wheel, though. Using `uniqid()` sounds a lit simpler than what you already tried, and is a lot safter (although not 100%) against identical values. Though the timestamp generated by `time()`, `microtime()` (which `uniqid()` is based on) are always the same, not affected by timezones set by PHP. – Qirel Oct 18 '16 at 13:25
  • Yeah you're absolutely right @Qirel, I'm just playing with PHP to see what type of tweaks I can do. – David Forestier Oct 18 '16 at 14:37
  • Thanks for the clarification about time() and microtime(), so their values and the way they are generated can't be hacked or changed? – David Forestier Oct 18 '16 at 14:37

1 Answers1

0

Try this, it is better than multiple rand() functions

$random_number ="0123456789";
$unique_id = substr(str_shuffle($random_number ), 0, 7);// add your unique_id  limit
echo $unique_id;
Dave
  • 3,073
  • 7
  • 20
  • 33