Skip to content
Advertisement

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

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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement