Created
March 2, 2017 10:22
-
-
Save DevStrefa/1ac0507a523558c72038c05ec3c8a261 to your computer and use it in GitHub Desktop.
Generate Random String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Generate random n-length string | |
* | |
* Method will generate random string based on given guidelines first parameter is length of returned string, | |
* next three parameters define which characters will be used to generate output. | |
* | |
* @param $length | |
* @param bool $alphabetCharacters if set to true, output may contain characters from aA to zZ (65-90 AND 97-122 in ASCII) | |
* @param bool $numbersCharacters if set to true, output may contain characters from 0 to 9 (48-57 in ASCII) | |
* @param bool $specialCharacters if set to true, output may contain special characters such as !*#,.;&$) etc. (33-47 AND 58-64 AND 91-96 AND 123-126 in ASCII) | |
* @return string | |
*/ | |
function generateRandomString($length,$alphabetCharacters=true,$numbersCharacters=true,$specialCharacters=true) | |
{ | |
if ($length <= 0){ | |
throw new \InvalidArgumentException('Output length must be at least 1 character long'); | |
} | |
$availableCharacters=array(); | |
$randomString=''; | |
if ($alphabetCharacters){ | |
$availableCharacters=array_merge($availableCharacters,range(65,90),range(97,122)); | |
} | |
if ($numbersCharacters){ | |
$availableCharacters=array_merge($availableCharacters,range(48,57)); | |
} | |
if ($specialCharacters){ | |
$availableCharacters=array_merge($availableCharacters,range(33,47),range(58,64),range(91,96),range(123,126)); | |
} | |
$lowIndex=0; | |
$highIndex=count($availableCharacters)-1; | |
if ($highIndex === -1){ | |
throw new \InvalidArgumentException('You must set at least one character group as allowed'); | |
} | |
for($i=1;$i<=$length;$i++){ | |
$randomString.=chr($availableCharacters[rand($lowIndex,$highIndex)]); | |
} | |
return $randomString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment