<?php
/* Sometimes it is required to create random strings, e.g. as unique keys, where using hash
* functions is not suitable. Remember, hash functions return a hexadecimal representation of a
* calculated checksum, i.e. a hash value only consists of [0-9a-f].
*
* To gain a wider range of characters used the following function might be more appropriate.
*/
/** $len : desired length of random string (should be smaller or equal to strlen( $abc ))
*/
function rand_str( $len )
{
// The alphabet the random string consists of
$abc = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// The default length the random key should have
$defaultLength = 3;
// Ensure $len is a valid number
// Should be less than or equal to strlen( $abc ) but at least $defaultLength
// Return snippet of random string as random string
}
// Example usage with a length of 25 chars
echo 'Your random string is: '.rand_str( 25 ); // Example output: Your random string is: URwXWGTMDAebriKmEV4zdqJ2I
/**Note that $abc gets shuffled in the above version.
* If a character is required to appear more than once, $abc must be tweaked e.g. as follows
* $rep : how often a char may be repeated
*/
function rand_str( $len, $rep )
{
// The alphabet the random string consists of
$abc = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// The default length the random key should have
$defaultLength = 3;
// The default count of repetitions of a char in the random string
$defaultRepetitions = 1;
// Ensure $len is a valid number
// Should be less than or equal to strlen( $abc ) but at least $defaultLength
// Max. repetitions of a char
// Should be less than or equal to $len but at least $defaultRepetitions
$rep = max( min( intval( $rep ), $len ), $defaultRepetitions );
// Expand $abc. Of course you may concatenate only parts of $abc here, too.
// Return snippet of random string as random string
}
// Example usage with a length of 25 chars and each char may appear up to 4 times
echo 'Your random string is: '.rand_str( 25, 4 ); // Example output: Your random string is: 0eMtcllvAAbPgOYO1CRcEBw0h
?>