How to Generate a Unique ID in PHP

Examples on How to Make a Random Unique User ID Using PHP

A unique user ID can be created in PHP using the uniqid () function. This function has two parameters you can set.

The first is the prefix, which is what will be appended to the beginning of each ID. The second is more_entropy. If this is false or not specified, it will return 13 characters; if it's true, 23 characters will be returned.

Examples For Creating a Unique ID

Below are examples of creating a unique user ID, but each are a little different.

The first creates a normal unique ID while the second shows how to make a longer ID. The third example creates an ID with a random number as the prefix while the last line can be used to encrypt the username before storing it.

 <?php 

//creates a unique id with the 'about' prefix $a = uniqid(about); echo $a; echo "<br>";

//creates a longer unique id with the 'about' prefix $b = uniqid (about, true); Echo $b; echo "<br>";

//creates a unique ID with a random number as a prefix - more secure than a static prefix $c = uniqid (rand (),true); echo $c; echo "<br>";

//this md5 encrypts the username from above, so its ready to be stored in your database $md5c = md5($c); echo $md5c; ?>

Format
mla apa chicago
Your Citation
Bradley, Angela. "How to Generate a Unique ID in PHP." ThoughtCo, Jan. 24, 2017, thoughtco.com/how-to-generate-unique-id-2694169. Bradley, Angela. (2017, January 24). How to Generate a Unique ID in PHP. Retrieved from https://www.thoughtco.com/how-to-generate-unique-id-2694169 Bradley, Angela. "How to Generate a Unique ID in PHP." ThoughtCo. https://www.thoughtco.com/how-to-generate-unique-id-2694169 (accessed May 27, 2018).