Generate compact random unique identifiers similar to video platform IDs using PHP

I need to create short unique identifiers in PHP that work like the ones you see in video sharing platforms. You know those random looking strings that appear in URLs? I want to generate something similar for my own project.

I’m looking for a way to make these IDs short but still unique enough that they won’t clash with each other. The goal is to have something that looks random and is hard to guess, but still keeps a reasonable length.

Here’s what I’m trying to achieve:

function createUniqueCode() {
    // Need implementation here
    return $randomId;
}

$newId = createUniqueCode();
echo $newId; // Should output something like: 'aB3xK9mP2'

What would be the best approach to generate these kinds of identifiers in PHP?

I’ve been working with similar ID generation for a content management system and found that combining uniqid() with additional randomization works well. The trick is to use uniqid() as a base since it includes microsecond timestamp data, then add your own random characters to make it less predictable.

Here’s what I settled on after testing different approaches:

function createUniqueCode() {
    $base = substr(uniqid(), -6);
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $random = '';
    for ($i = 0; $i < 5; $i++) {
        $random .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return str_shuffle($base . $random);
}

This gives you 11-character IDs that look random but have good uniqueness properties. The uniqid() part ensures time-based uniqueness while the random characters add unpredictability. I’ve generated millions of these without collisions in production use.

honestly just use bin2hex with random_bytes - way simpler than overthinking it. bin2hex(random_bytes(5)) gives you 10 char hex strings that are cryptographicaly secure. been using this for years without issues and it’s readable code that any dev can understand immediatly.

Base64 encoding with random bytes has served me well for this exact purpose. The key advantage is you get a good balance between length and uniqueness without overthinking the character selection process.

function createUniqueCode() {
    $bytes = random_bytes(8);
    $encoded = base64_encode($bytes);
    return rtrim(strtr($encoded, '+/', '-_'), '=');
}

This approach generates 8 random bytes then converts them to a URL-safe base64 string, removing padding characters. You end up with roughly 11 characters that are genuinely random and cryptographically secure thanks to random_bytes(). I’ve used this method across multiple projects including a file sharing service where collision avoidance was critical. The URL-safe character substitution means these IDs work perfectly in web addresses without encoding issues.