12-05-2011, 02:38 PM
PHP Code:
function GeneratePass($length = 5){
$length = (INT)$length; //Type cast our variable to be an integer. If anything other than an integer was submitted, it will now equal 0 (With the exception of
//the boolean value 'true', which will cause the variable to now equal one.
if ($length <5){ //The minimum length for the password is five, anything less isn't worth the time it takes to process.
$length = 5;
}
$alphabet = explode(",", "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0");
$numbers = explode(",", "1,2,3,4,5,6,7,8,9,0");
$symbols = explode(",", "!,£,$,%,^,&,*,(,),{,},~,@,:,;,#,?,/,>,.,<");
//Split all the available letters, numbers and symbols up into an array.
$pass = ""; //Declare our password
while(strlen($pass) < $length){
if (strlen($pass) == ($length -1)){
$choose = rand(0, (sizeof($symbols) -1));
$pass .= $symbols[$choose];
}elseif (strlen($pass) >=($length - 3)){
$choose = rand(0, (sizeof($numbers) -1));
$pass.= $numbers[$choose];
}else{
$choose = rand(0, (sizeof($alphabet) -1));
$pass .= $alphabet[$choose];
}
}
Return mysql_real_escape_string(strip_tags($pass));
}
Above is a function which will generate a password of a given length. A minimum length of 5 is required. The generated password is then sanitised ready for use in a database.
The given password will be in the following format:
[(Given length -3)X A-Z] [2X 0-9] [1 X Symbol]
Example:
PHP Code:
GeneratePassword(15)
Output: aAWfUxZyGTeb56%
Usage:
PHP Code:
GeneratePassword(LENGTH)