Haxans web - The Internet Resource

Home|Contact Us
Home·Articles·Tutorials·Reviews·Templates·Free Stuff

Generating random passwords


Author: david | Posted On: 20 April 2007 | Views: 6893

It becomes practical and more useful if the tutorial is written in the form of a funtction. This function will hopefully work anywhere.

The basic idea behind this random password is that it will give a different password every time it is called. This can only be done by using the time as the main core input.  So we will start of by defining a PHP function which will generate this password for us. There will be one input from the user, the length of the password. When the function will be called, it will return a random password of characters ranging from 0-32 depending on the length given (alphabets and numbers).

Here is the complete function:

<?php
function randomPassword($length){

  $pass md5(time());
  $pass substr($pass, 0, $length);
  return $pass;
}
?>

The above function is pretty straight forward. The first line defines a function called "randomPassword" which takes a parameter 'length'. The next line uses the built-in PHP function MD5(). MD5 function returns the hash of the input given. Here we give MD5 the time as input. The time() function returns the timestamp. Remember that the timestamp will always be different because the date is always changing (here date includes time and seconds). So basically when we give the MD5 function the latest timestamp, it generates the hash for that specific instant, which is also always different because of the ever changing time.

Next we substr the password returned. Substr is used for returning some specific length of a given string. For example, the substr used here will return the initial string of the password of the length that the user will give.

The last line of code returns the password randomly generated.

You can use the function the following ways:

<?php
echo randomPassword(15);
//or
$password = randomPassword(15);
?>

The above code will return something like 1b415353bde123a

 Enjoy the tutorial, hopefully your brain is already thinking of dozen places to use this function e.g forum activation code etc.





Post A Comment
    Name:

Website:



© Copyright 2007 www.haxansweb.com - Haxan. All Rights Reserved. Privacy Policy.