How to create a random password at any length.
TAGS: Random, Password, PHP


When you have users signing up to your website, you often want to generate a password for them. There are of course different ways to do this. I give you one here that works for me.

We make a function containing the code. In this example the function is called straight away, so you see the result instantly. But we can call it where we need it in our program, and get a password in return.

Like this:

$MyPass  = generate_pass(6); 

Now $MyPass holds the password just created, and can be used in the code.
<?php 

function generate_pass($length) { 
  $charsstring = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789'; 
  $countchars = mb_strlen($charsstring); 
  
  for ($i=0, $result=''; $i<$length; $i++) { 
    $index = rand(0, $countchars-1); 
    $pass = $pass . mb_substr($charsstring, $index, 1); 
  } 
  return $pass; 
} 

// Here we call the function, and get the new password back
$MyPass  = generate_pass(6); 
// Here we print the new password to the browser
echo "Hey! You have a password..

"; echo $MyPass; ?>


I have removed I, l, L, i, o, O, 0, 1 from the list of numbers, and characters in the alphabet, to avoid mistakes.
Try to change the value from 6 into some other value giving the length of the password.