

The problem with rand and mt_rand is that they are not cryptographically secure.
#PHP RANDOM PASSWORD GENERATOR CODE#
This made us wince, as they are essentially polluting “the PHP sphere” with insecure code when there are more secure and easy-to-use alternatives out there. One of the reasons that we wrote this tutorial is because we came across a number of similar guides that recommended the use of functions such as rand or mt_rand. Why did you use random_int instead of rand or mt_rand?


We created a string of all the characters that our function can use while generating the password.You can also use it to suggest a new secure password to the user. This kind of function is especially useful for creating one-time passwords (OTP) and other important tokens. The custom PHP function above will generate a random string and then return it.Īll you have to do is specify the length of the string by passing in the $length parameter. Loop from 1 to the $length that was specified. $characterListLength = mb_strlen($characters, '8bit') - 1 Get the index of the last character in our $characters string. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!-.?*()' A list of characters that can be used in our * int $length The length that you want your random password to be. * A PHP function that will generate a secure random password. Take a look at the following function: /** To do this, we will be using the random_int function, which is cryptographically secure.
#PHP RANDOM PASSWORD GENERATOR HOW TO#
In this tutorial, we are going to show you how to generate a secure random password using PHP.
