Password Generator

Password Generator

Web Stuff 11.10.2015 3574


Password Generator

Simple password generator build with a Javascript or PHP function. Two password generator functions one is build on pure Javascript and one on PHP. Easy to use plus you can choose the length of the password with just changing the number when calling the function.

Like to try?

Javascript

/* Password Generator */
var el = document.getElementById("create-password");
var el1 = document.getElementById("new-password");
el.addEventListener("click", function() {

var newPass = randomStr(10);
// Simple password with a maximum of 10/11
// var newPass = Math.random().toString(36).substr(2, 8);
el1.innerHTML = newPass;

});

// Function to generate a random string with predefined characters.
function randomStr(m) {
var m = m || 9; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
return s;
};

Le't brake it down block by block.

var el = document.getElementById("create-password");
var el1 = document.getElementById("new-password");

This two variable will find the input field or div which has the ID "new-password and the button which will have the ID "create-password".

el.addEventListener("click", function() {

var newPass = randomStr(10);
// Simple password with a maximum of 10/11
// var newPass = Math.random().toString(36).substr(2, 8);
el1.innerHTML = newPass;

});

The click even listener for the button. We have two options, either we call the simple password one liner (see below) that can create a password with maximum 11 characters.

var newPass = Math.random().toString(36).substr(2, 8);

or we call following function:

// Function to generate a random string with predefined characters.
function randomStr(m) {
var m = m || 9; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
return s;
};

This will give us much more options with unlimited characters. You can define the characters in the "r" variable and you are not limited to 11 characters.

PHP

In php the function is much simpler:

// Password generator
function jak_password_creator($length = 8)
{
return substr(md5(rand().rand()), 0, $length);
}

To create a new password you call the function like this:

$newpassword = jak_password_creator();

This will create random password with 8 characters, if you like a password with 10 characters you call the function like this:

$newpassword = jak_password_creator(10);

Can be used when calling a forgot password procedure or a simple user registration where the password is mailed to.

Hope you like another tutorial from JAKWEB. We are looking forward for your feedback.