For generating random string i written code like this But if the function is called with a negative value, or zero, or 1 million it will create lot of problems. So please suggest me better code.
/*
* The following function is for generating a random string value.
* @param unknown_type $length
* @return string $randString
*/
function generateRandomString( $length ) {
$randString = "";
srand();
$characters = "abcdefghijklmnopqrstuvwxyz1234567890";
/*
* build string of random characters
*/
while( strlen( $randString ) < $length ) {
$randString .= substr( $characters, rand() % (strlen( $characters )),1 );
}
return $randString;
}
To stop the negative number or zero passed as an argument as being a problem, you could use
max(1, $length). Alternatively, check for< 1and throw an exception or returnFALSE.Here are some suggestions for your code…
CodePad.
Note that this won’t ever have the same character twice in the resulting string.
If you do desire that, you could use something like…
CodePad.
…or slightly different…
CodePad.