New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home php codes How to Generate a Random Password in Php

How to Generate a Random Password in Php


Welcome Back to
today we will learn how to generate a random password with the help of php script .
In our previous post we learn how to check password and confirm password are same.
It’s always better to use a randomly generated password rather than your name,birthdate, city,state or your lover name.

random password generate in php

Nowadays most of the registration/signup forms like (Online Banking System, E-commerece Websties) require you to input a secure password and show you a warning
if the password is too simple or easy to hack.
If you are creating a registration/signup system for your PHP project, it will be useful to suggest a password to people who register to your
website Using PHP, it’s pretty easy to generate a random password.

Using the function below you can specify what kind of symbols your password 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.

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(15,1,"lower_case,upper_case,numbers,special_symbols");
foreach($my_passwords as $pass)
    echo $pass;