go top

Generate a random password with PHP

In this tutorial, you will find out how to generate random passwords with a handy PHP function.

It's always better to use a randomly generated password rather than your name, birthday, city, etc. Nowadays most registration forms require you to input a secure password and show you a warning message if the password is too simple. If you are creating a registration system for your PHP project, it will be useful to suggest a password to people who register. Using PHP, it's pretty easy to generate a random password.

Using the function below you can specify what kind of symbols your password(s) should contain, what the password length should be, and how many passwords you want to generate. The output will be an array with generated password(s).


function randomPassword($length,$count, $characters) {

// $length - the length of the generated password
// $count - number of passwords to be generated
// $characters - types of characters to be used in the password

// define variables used within the function
$symbols = array();
$passwords = array();
$used_symbols = '';
$pass = '';

// an array of different character types
$symbols["lower_case"] = 'abcdefghijklmnopqrstuvwxyz';
$symbols["upper_case"] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$symbols["numbers"] = '1234567890';
$symbols["special_symbols"] = '!?~@#-_+<>[]{}';

$characters = split(",",$characters); // get characters types to be used for the passsword
foreach ($characters as $key=>$value) {
$used_symbols .= $symbols[$value]; // build a string with all characters
$symbols_length = strlen($used_symbols) - 1; //strlen starts from 0 so to get number of characters deduct 1

for ($p = 0; $p < $count; $p++) {
$pass = '';
for ($i = 0; $i < $length; $i++) {
$n = rand(0, $symbols_length); // get a random character from the string with all characters
$pass .= $used_symbols[$n]; // add the character to the password string
$passwords[] = $pass;

return $passwords; // return the generated password

$my_passwords = randomPassword(10,1,"lower_case,upper_case,numbers,special_symbols");



Here are a few examples how to generate different random passwords using PHP

// generate one password using 5 upper and lower case characters

// generate three passwords using 10 lower case characters and numbers

// generate five passwords using 12 lower case and upper case characters, numbers and special symbols

Hope this tutorial was useful for you! Good luck with your projects!

0 Comments to "Generate a random password with PHP"

Add your comment

    • Free Scripts

      Add great new functionalities to your website with our Free Scripts collection.

      Free scripts
    • PHP Scripts

      Check our extensive collection of top-notch PHP Scripts that will enhance your website!

      Commercial PHP scripts