Generate a password using PHP
How do you generate a strong random password using 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.
I have removed I, l, L, i, o, O, 0, 1 from the list of numbers, and characters in the alphabet, to avoid mistakes.
You can add any characters that you want. Perhaps some special characters, like #, £, @, $ and so on. Just add them to the list of the existing characters.
If you want some characters to be occuring more often, f.ex the special chars, then just add them multiple times on the list.
HTML
Call the script in this way. If you want it to be f.ex 8 characters long.
<HTML><BODY>
<?php
$MyPass = generate_pass(8);
?>
</BODY></HTML>
PHP
Sometimes you have to find some cryptic password. Either for your users, or you like a machine to generate passwords to your own use.
This script will generate a strong password, in any length that you desire. See on the HTML tab how you call this script.
<?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;
}
$MyPass = generate_pass(8);
echo "Hey! You have a password..";
echo $MyPass;
?>