Generate random string in php
Generate random string in php
In the development of web applications, generating random strings can be very useful in a lot of cases. It might be for a verification code or a password etc. There different types to generate random string in php
Below is a simple function to generate a random string, this function takes the length and special character value. if not pass the value it will set a default 12 character string without the special character and based on this value random string will be generated.
function getRandomString($maxlength=12, $isSpecialChar=false)
{
$randomString=null;
//initalise the string include lower case, upper case and numbers
$charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//if required special character to include, please set $isSpecialchar= 1 or true
if ($isSpecialChar) $charSet .= "~@#$%^*()_±={}|][";
//loop for get specify length character with random characters
for ($i=0; $i<$maxlength; $i++) $randomString .= $charSet[(mt_rand(0,(strlen($charSet)-1)))];
//return the random string
return $randomString;
}
//call the function set value you required to string length default:12
$random8char=getRandomString(8);
echo $random8char;
//call the function and set second parameter true to add special character
/*
$random8withSpecialChar=getRandomString(8, true);
echo $random8withSpecialChar;
*/I hope you like this Post, Please feel free to comment below, your suggestion and problems. I will try to give the answer to your queries
Other PHP topics click below link
