Create a random password with PHP

Some websites require access control, and sometimes you may need to generate a password for a user. Here’s a simple function that can do just that.

The $base-variable contains the characters allowed in the password. The supplied string may be changed, but the selected charaters should exist on all keyboards (as far as I know). When calling the function, you can specify the lenght of the password you want. Simple, right?

1
2
3
4
5
6
7
8
9
10
function makePassword($desiredLenght = 8) {
$password = '';
$base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
 
for($i=0;$i<$desiredLenght;$i++) {
$password .= $base[(rand(0, (strlen($base)-1)))];
}
 
return $password;
}