View Full Version : Random String Generator

06-27-2005, 08:08 PM
Is there anyway to create a random string of characters/numbers/symbols in php and then add it to a text box on a page?

06-27-2005, 08:20 PM
For the numbers you could use rand() (http://us2.php.net/manual/en/function.rand.php) .

For the characters, symbols: you put all the characters of the english language into one array, and whatever symbols you want to use into another array....then you can use array_rand() (http://us2.php.net/manual/en/function.array-rand.php) to pick several random elements from each of these arrays...

Then use concatenation to string them together into a larger string....the result would look like:


There might be a better way to do this, but that's certainly one way...

06-27-2005, 08:26 PM
This should generate a string out of any normal character:

function rand_str($len)
$str = '';
for($i = 0; $i < $len; $i++)
$str .= chr(mt_rand(32, 126));
return $str;

06-27-2005, 08:37 PM
So that function returns a longish number that reads as a string, right marek?

06-27-2005, 08:58 PM
It accepts the length as argument.

06-27-2005, 11:55 PM
Thanks alot. :)

Um, I'm very new to php so how would I say have that function in page - when a button is clicked, the function is run and a text box shows the random string...? :o

06-28-2005, 12:07 AM
You can either reload the same page when submit button is pressed, by setting the action of the form equal to:

<form method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">

or load another page:

<form method="post" action="another_page.php">

Whichever one you use, that is where you will execute the function in your script....

Then, after the script has run, set the value of your target textbox to whatever variable you assigned to your random string of characters:

If your random string of characters is set to $random_string, then the text box code would be:

<input type="text" name="name" value="<? echo $random_string; ?>">

06-28-2005, 12:08 AM
The page with the function is called. Anywhere you like you just print what the function returns. Example:

<input type="text" value="<?php print rand_str($length);?>">

06-28-2005, 11:13 AM
Thanks, that's helped alot. :)