How can I make short random unique keys, like YouTube video IDs, in PHP? [closed]

Solution 1:

The idea is to convert a unique integer (such as current time) in an other mathematical base.

A very simple way in PHP :

// With this precision (microsecond) ID will looks like '2di2adajgq6h'

// From PHP 7.4.0 this is needed, otherwise a warning is displayed
$cleanNumber = preg_replace( '/[^0-9]/', '', microtime(false) );
$id = base_convert($cleanNumber, 10, 36);


// With less precision (second) ID will looks like 'niu7pj'

$id = base_convert(time(), 10, 36);

Solution 2:

A small PHP class to generate YouTube-like hashes from one or many numbers. Use hashids when you do not want to expose your database ids to the user.

Source: https://github.com/ivanakimov/hashids.php

Solution 3:

Use whichever you like :-)

// Generates Alphanumeric Output

function generateRandomID() {
    // http://mohnish.in
    $required_length = 11;
    $limit_one = rand();
    $limit_two = rand();
    $randomID = substr(uniqid(sha1(crypt(md5(rand(min($limit_one, $limit_two), max($limit_one, $limit_two)))))), 0, $required_length);
    return $randomID;
}

// Generates only alphabetic output

function anotherRandomIDGenerator() {
    // Copyright: http://snippets.dzone.com/posts/show/3123
    $len = 8;
    $base='ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz';
    $max=strlen($base)-1;
    $activatecode='';
    mt_srand((double)microtime()*1000000);
    while (strlen($activatecode)<$len+1)
    $activatecode.=$base{mt_rand(0,$max)};
    return $activatecode;
}