Generate Random Strings Using PHP

random_string_featured

This is a quick tutorial to show you how to generate random strings with PHP. Random strings are useful for renaming uploaded files or sending unique activation codes to users and many other purposes. In this post I will suggest more than one method and you can choose what is more suitable for your project.

md5()

<?php
  $randomString = md5(time());
?>

This is the most simple way to generate a unique string. time() produces a unique timestamp, were it stores the number of elapsed seconds since 01/01/1970 so it is constantly changing and md5() is guaranteed to hash a unique string each time. However, this method is not secure for really busy survers with thousands of transactions, for example imagine you are using this method to generate a random file name for an uploaded file and then you have two users uploading a file at the same exact time, then time() will return the same string and hence md5() will produce the same random string and the uploaded files will overwrite one another.

If you use this function to generate random file names and for really active websites with thousands of transaction you might risk files overwriting one another.

Pros:

  • Very smart and simple.
  • Efficient for small websites.
Cons:

  • Fixed string length (only 32 chars).
  • Contains only letters [a-z] and numbers [0-9] but does not contain special characters.
  • Contains only lower case letters
  • md5() has a collision rate, however the chances of that happening are very slim. If you look at two arbitrary values, the collision probability is only 2-128.

mt_rand()

I personally prefer this method because it addresses all issues associated with using md5().

<?php
	function gen_random_code($length) {
		$characters = "abcdefghijklmnopqrstuvwxyzABCDERFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";  
		$randomString = ""; 
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[mt_rand(0, strlen($characters)-1)];
		}
		return $randomString;
	} 
?>

Using this method, the user can pass the desired string length as a function parameter.
The $characters string holds all possible characters that can appear on the final random string.
mt_rand(int $min , int $max) takes two parameter minimum and maximum values and produces an integer between the gives values inclusive. If you want a random number between 5 and 15 (inclusive), for example, use mt_rand(5, 15).
The string $randomString starts storing a random character chosen from the $characters string until the for loop reaches the length specified by the $length parameter.

Pros:

  • Flexible string length.
  • Can contain lower and upper case letters as well as numbers and special characters
  • No collision rate
Cons:

  • NA


If you are interested in using this method for renaming uploaded files please visit Smart Way for Renaming Uploaded Files Using PHP.

Thank you for reading. If you like this post please share, tweet, +1 etc.

You can also let me know if this post was helpful to you by leaving a comment.

If you have any questions or would like me to discuss a certain topic please send me a message or simply just leave a comment below!

Generate Random Strings Using PHP
5 votes, 3.80 avg. rating (76% score)
  • Posted in: PHP
Husamaldin Tayeh

Posted by

Husamaldin is a computer programmer, blogger, entrepreneur and an overall thinker. He is the founder and editor of Coders Mount. He loves everything about computers and programming. Find out more about him here or follow him on Twitter Google+ | LinkedIn.

  • Guest

    Well done Husam! :)