Generating unique IDs and random strings in PHP

PHP functions covered in this tutorial:

  • uniqid()
  • md5()

This tutorial explains how to create unique ID strings using the uniqid() function and random strings using the md5() function. Warning: The uniqid() function does not create random or unpredictable strings. The uniqid() function should not be used for security purposes. For this purpose, it is better to use a secure string function or create a hash instead. You can create different types of hashes such as md5, sha1 or sha256. We will just look at the md5 hash in this tutorial.

Watch the video below and then scroll down to see the sample PHP code.

Sample PHP code:

<?php
  // Warning: The uniqid() function does not create random or unpredictable strings.
  // The uniqid() function should not be used for security purposes. Use a secure
  // string function instead.

  echo uniqid(); // generates unique ID
  echo '<br>';
  echo uniqid('id'); // generates unique ID with prefix of 'id'
  echo '<br>';
  echo uniqid('id',true); // generates unique ID with prefix of 'id' and increased entropy
  echo '<br>';
  echo md5(time() . mt_rand(1,1000000)); // using md5 to create random string
?>