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

kusanagi picture kusanagi · Oct 21, 2010 · Viewed 32k times · Source

Is there any way to create unique keys like those used in YouTube video urls (ex: https://www.youtube.com/watch?v=nWChTnkVdKE)?

Answer

Diantre picture Diantre · Jan 27, 2015

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