• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

IntenseClick

  • Home
  • WordPress
  • Ethical Hacking
  • Coding
Home » Generate secure and random password using PHP

Generate secure and random password using PHP

April 30, 2023 by ιnтenѕeclιcĸ Team Leave a Comment

Lets understand first what we are going to achieve with our code –

  1. Define the length of the password: Start by defining the length of the password that you want to generate. For example, let’s set the length to 8 characters.
  2. Define the character set: Next, define the character set from which the password will be generated. This can include uppercase and lowercase letters, numbers, and special characters. For this example, we’ll use all four of these categories.
  3. Generate the password: Use a loop to randomly select characters from the defined character set and append them to a string until the desired password length is reached.
  4. Shuffle the password: After generating the password, it’s a good idea to shuffle the characters to make the password even more secure. This can be done using the str_shuffle() function in PHP.
  5. Return the password: Finally, return the randomly generated and shuffled password as a string.

 

function generateRandomPassword($length = 8) {
    // Define character set
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
    
    // Generate password
    $password = "";
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[rand(0, strlen($chars) - 1)];
    }
    
    // Shuffle password
    $password = str_shuffle($password);
    
    // Return password
    return $password;
}


$password = generateRandomPassword(12);
echo $password; // Output: r$#x8z%J0F9@


This will generate a random password of 12 characters using the defined character set, shuffle the characters, and return the password as a string.

More tech articles

Change HTML webpage color randomly on refresh and interval
Service host superfetch – slow pc ,high disk usage, disk full fix(svchost.exe)
Service Host Superfetch
What is Service Host Superfetch and How to Fix it
How To Fix Microsoft Compatibility Telemetry High Disk Usage Issue On Windows
PHP code for login page script
How to Install Maven on Windows 2023 | Project management tool for Java applications

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Footer

insightful tech editorials to distribute useful tech guides and resources for free.

[email protected]

  • About us
  • Guest Post/Content Writing
  • Terms & Conditions
  • Privacy Policy
  • Disclaimer
  • Contact us

ιnтenѕeclιcĸ · © 2025