Random String Generator
The following generates a pseudo random string using the PHP function mt_rand(int $min, int $max): int
. The resulting string contains upper and lower case letters (a-z og A-Z) and intergers (0-9) in a statistical 50-50 mix of letters and numbers. Use for generating e.g. temporary passwords or tokens. Input desired output length and click!
Though for cryptographic purposes one should rather use the function random_bytes(int $length): string
.
Source Code
random_string.php
<?php
// Print a pseudo random string 20 characters long:
echo getRandomStr(20);
/**
* Creates a pseudo random string of the specified length from the
* characters a-z, A-Z (50%), and 0-9 (50%).
* @param $length int The length of the string to be created.
* @return String The random string created.
*/
function getRandomStr(int $length = 20): string
{
$randomStr = "";
for ($i = 0; $i < $length; $i++) {
$n = mt_rand(1,4);
if ($n == 1) {
$randomStr .= chr(mt_rand(65,90)); // ASCII-values capital letters
}
elseif ($n == 2) {
$randomStr .= chr(mt_rand(97,122)); // ASCII-values small letters
}
else {
$randomStr .= chr(mt_rand(48,57)); // ASCII-values numbers
}
}
return $randomStr;
}
?>