...

View Full Version : Random String Generator



mark87
06-27-2005, 09: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?

chump2877
06-27-2005, 09: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:


3494ejdf&*#%

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

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


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

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

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

mark87
06-28-2005, 12:55 AM
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

chump2877
06-28-2005, 01: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; ?>">

marek_mar
06-28-2005, 01: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);?>">

mark87
06-28-2005, 12:13 PM
Thanks, that's helped alot. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum