user5305868
user5305868

Reputation:

ID Generating algorithm similar to youtube's generation

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.

Upvotes: 2

Views: 81

Answers (1)

Federkun
Federkun

Reputation: 36964

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());

Upvotes: 1

Related Questions