Write a PHP script that generates a random password of a specified length.

<?php
function generateRandomPassword($length) {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+';
    $password = '';

    for ($i = 0; $i < $length; $i++) {
        $randomIndex = rand(0, strlen($characters) - 1);
        $password .= $characters[$randomIndex];
    }

    return $password;
}

$passwordLength = 12;
$randomPassword = generateRandomPassword($passwordLength);

echo "Random Password: $randomPassword";
?>
  • The script defines a function generateRandomPassword that generates a random password of a specified length.
  • It uses a string of characters ($characters) that includes lowercase and uppercase letters, numbers, and special characters.
  • The for loop iterates through the specified length, selecting random characters from the character set.
  • The script then calls the function with a sample password length ($passwordLength) and prints the result.

Post your Answer