[Tutorial] Create A Generated Random Password

In this tutorial, I will show you how simple it is to generate a random password. First off, I would like to clarify that this method is not limited to just the generation of random passwords, but it can also be used to generate a random string for other purposes.

To keep things simple, we are going to create a function that allows you to generate your random password without cluttering your existing code with extra lines.  I am going to split this tutorial in to two different segments.  The first segment will be a basic method that allows the developer to define the length of the string.  The second segment will be a more advanced method that allows the developer to define the length as well as the complexity of the string.


Basic Version – Alphanumeric Password

Alright so this is the first segment of the tutorial.  This basic version will generate a random password that is alphanumberic (made of letters and numbers).  To keep your existing code less cluttered, we are going to create a PHP function named generatePassword().  Here is the function that you need to copy to the top of your PHP file after <?php.

<?php
function generatePassword($length=10) {
	$chars = "023456789abcdefghijkmnopqrstuvwxyz";
 
	$i = 0;
	$str = "";
	while ($i<=$length) {
		$str .= $chars[mt_rand(0,strlen($chars))];
		$i++;
	}
	return $str;
}
?>

Now I am going to explain a few core functions that have been used in the above code.  The while() function will continue to loop the code that selects a character until the length of the string is at the set amount.  mt_rand() is used to pick a random character from possible list of characters inside the variable $chars.  strlen() is used to determine the amount of possible characters from $chars.

The default length of the random string is 10 characters long, however that can be changed on-the-fly.  In order to display the random string you can use this code below:

1
2
3
4
<?php
echo generatePassword(); // Displays a 10 character string
echo generatePassword(7); // Displays a 7 character string
?>

So if you use the code from Line 2, it will display a string 10 characters long, which is the default length.  If you use the code from Line 3, it will display a string 7 characters long because that is the length you defined when executing the function.

So there you have it, that is a basic yet powerful function to create a random alphanumeric password (or string) at your desired length.  In the next segment, you will see how we could make this basic function and turn it in to something much more powerful.


Advanced Version – Multiple Levels of Complexity

For those of you that want to have more control and higher security, this advanced version of the previous segment meets that goal.  This advanced version uses the core functions and structure of the basic version, however has a few additions to improve it.

To use this version, remove the function you added at the beginning of the file in the basic version (if you even used it), and replace it with the new function written below:

<?php
function generatePassword($level=3,$length=10) {
	$chars[1] = "1234567890";
	$chars[2] = "abcdefghijklmnopqrstuvwxyz";
	$chars[3] = "023456789abcdefghijkmnopqrstuvwxyz";
	$chars[4] = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
	$chars[5] = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ!@#$%^&*?=+-_";
 
	$i = 0;
	$str = "";
	while ($i<=$length) {
		$str .= $chars[$level][mt_rand(0,strlen($chars[$level]))];
		$i++;
	}
	return $str;
}
echo generatePassword();
?>

The only thing we changed was that we introduced multiple levels of complexity by adding more possible characters in each level.  Listed below is a description of each level available.

  • Level 1 – Numeric Pin
  • Level 2 – Alphabetic Password
  • Level 3 – Alphanumeric Password (Default)
  • Level 4 – Alphanumeric w/ Capital Letters
  • Level 5 – Alphanumeric w/ Capital Letters & Symbols

The default setting of complexity is level 3, which is the same as the basic version.  You can easily define the level of complexity and length of the string by using the examples below:

1
2
3
4
<?php
echo generatePassword(); // Level 3 string with 10 characters
echo generatePassword(5,12); // Level 5 string with 12 characters
?>

Line 2 will display a [level 3] alphanumeric string with 10 characters.  Line 3 will display a [level 5] alphanumeric (w/ uppercase letters & symbols) that is 12 characters long.

So if you want full control on-the-fly for how complex and the length the string should be, the advanced version is the method you will want to choose.


Quick Tips

You may have noticed that a few characters are missing from the list of possible characters.  This is not a typo, I purposely removed some characters as they look alike and may be confused for one another.  Below is a list of removed characters:

  • Removed l (lowercase letter L) and 1 (number one) from levels 3, 4, and 5
  • Removed O (capital letter O) and 0 (number zero) from levels 4 and 5

If you would like to assign a random string to a variable, you can use the example below:

<?php
$username = $_POST['username'];
$password = generatePassword();
echo "Username: ".$username."<br />";
echo "Password: ".$password."<br />";
echo "Make sure you save this somewhere safe!";
?>

Conclusion

So that is the end of this two-part tutorial.  The first segment of this tutorial should help people who are looking for basic generation of a random password/string, the second segment allows for increased customization to provide better control over the generation of a password/string.  The default settings of each version result in the same level of complexity and length string.

This entry was posted in PHP Tutorials, Tutorials and tagged , by Brandon Enriquez. Bookmark the permalink.

About Brandon Enriquez

Brandon has been around Prosoft Studio since the very beginning of the company back in the summer of 2007. As the founding member, he has laid out a vision of providing the best professional software and offering methods of teaching others some of his own knowledge. He is very experienced in (X)HTML, CSS, JavaScript, PHP, and SQL programming languages. He is also experienced in Adobe Photoshop for website design and graphic designs such as logos, banners, and other media.