php

Generate unique id PHP

<?php
    //Using uniqid()
    $uid = uniqid();
    echo $uid;

    //Using random_bytes and bin2hex
    $ran_bytes = random_bytes(15);
    $uid = bin2hex($ran_bytes);
    echo $uid;

    //USING md5
    $str = "uname";
    $uid = md5($str);
?>

To create a unique id using PHP, you can use inbuilt function uniqid() that generates the unique id based on current time in micro seconds. But it may not guarantee to be unique always. You can make it more unique using bin2hex() function or combination of that.

You can use bin2hex() method which can be useful to generate uniqe id. We are also using random_bytes(15) method to generate random bytes and passing it to bin2hex to generate a unique id.

Was this helpful?