Skip to content
PHP Logo

In the PHP code provided for generating a password, what does the srand function do and why is it used?

The srand function initializes the random number generator in PHP. It is used to seed the random number generator with a specific value, ensuring that the sequence of random numbers generated is different each time the script is run. This is important when generating secure passwords to avoid predictable patterns.

php
<?php
function generatePassword($length = 12) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()';
    $password = '';
    
    srand(); // Initialize the random number generator
    
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[rand(0, strlen($chars) - 1)];
    }
    
    return $password;
}

echo generatePassword(); // Output a randomly generated password
?>