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

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

Leave a Comment