How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
First make a string with all your possible characters:
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
You could also use range() to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:
$string = '';
for ($i = 0; $i < $random_string_length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
$random_string_length is the length of the random string.
Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
To make one that is seven characters long like your example above, just try this:
$unique_key = substr(md5(rand(0, 1000000)), 0, 7);
The code sample at Generate Random Strings Using PHP allows you to do just that. With little knowledge of php, you can customize that function to get the type of random strings you need:
- only characters e.g. ucvtbp3v
- mix of digits and characters e.g. 9JP2E06R
- mix of characters, digits and symbols e.g. 2sczkf-j
You have missing parenthesis in your post for the rand() function Jeremy.
Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().
<?php
$character_array = array_merge(range(a, z), range(0, 9));
$string = "";
for($i = 0; $i < 6; $i++) {
$string .= $character_array[rand(0, (count($character_array) - 1))];
}
echo $string;
?>
This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().
Maybe I missed something here, but here's a way using the uniqid() function.