2

I am generating random IDs for polls; I have removed enumerating IDs for obvious reasons. I have made my own function for generating the IDs but I'm not sure if it's very 'optimised' or if I'm not doing it the right way. Once I hit near 64^6 polls (probably NEVER going to happen) it would lag. Is this very good?

function generateID() { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'; $id = $this->injectionCSC('$' . substr(str_shuffle($chars), 15, 10), true); $link = $this->connect(); $query = mysqli_query($link, "SELECT * FROM polls WHERE id='$id'"); if (mysqli_num_rows($query) > 0) { $id = $this->generateID(); } return $this->injectionCSC($id, false); } 

$this->injectionCSC($id, false/true); is just a function to get rid of sql injection and html tags. If I'm correct in saying, this current ID generating function can hold up to 1.8014399e+16 polls. And to increase the amount I could either change the special char at the front ('$') or just add another character.

2
  • You need some random id? Use UUID Commented Apr 9, 2016 at 12:26
  • @Federico please give an example? I want it to be base64 (has 64 characters to choose from). Commented Apr 9, 2016 at 12:28

1 Answer 1

1

Instead of using pseudorandom number generator to generate your unique ids, choose UUID.

UUIDs v4 are unique and extremely unlikely to collide, unlike your str_shuffle implementation. You can use ramsey/uuid package to do that. It's simple as write:

$uuid4 = (string) Uuid::uuid4(); // something like 16fd2706-8baf-433b-82eb-8c7fada847da 

You can take the raw bytes to encode them using base64:

$id = base64_encode(Uuid::uuid4()->getBytes()); 
Sign up to request clarification or add additional context in comments.

3 Comments

Is this acceptable? $rawId = sprintf($yearIdentifier . '%04X%04X%04X%04X%04X%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)); echo('$' . substr(base64_encode($rawId), 32, 9));
I don't think so, at that point just generates 128 bits of random data with openssl_random_pseudo_bytes(16); and then convert them in base64 -> $id = base64_encode(openssl_random_pseudo_bytes(16));
Thanks @Federico , new code = $id = substr($this->getYearIdentifier() . str_replace('/', '_', str_replace('=', '-', str_replace('+', '-', base64_encode(openssl_random_pseudo_bytes(15))))), 0, 10); $link = $this->connect(); if(mysqli_num_rows(mysqli_query($link, "SELECT * FROM polls WHERE id='$id'")) > 0) { $id = $this->generateID(); //recursion until it's not used. } return $id;