Forum Moderators: coopster

Message Too Old, No Replies

generating random strings

         

laura2k

2:51 am on Dec 11, 2003 (gmt 0)



hello,

i need a php code that will randomly generate a alphanumeric string that i can use

i came across one at i-fubar.com/random-string-generator.php but the problem is i dont understand it, the person hasnt give the code in complete.

can anyone help?

thanx in advance.

jatar_k

3:39 am on Dec 11, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



paste the 2 functions into a file one after the other. At the end of the 2 functions put the actual call to the function.

like so

<? 
function assign_rand_value($num) {
// accepts 1 - 36
switch($num) {
case "1":
$rand_value = "a";
break;
case "2":
$rand_value = "b";
break;
<lots of other code>
case "35":
$rand_value = "8";
break;
case "36":
$rand_value = "9";
break;
}
return $rand_value;
}
function get_rand_id($length) {
if($length>0) {
$rand_id="";
for($i=1; $i<=$length; $i++) {
mt_srand((double)microtime() * 1000000);
$num = mt_rand(1,36);
$rand_id .= assign_rand_value($num);
}
}
return $rand_id;
}
$mybignum = get_rand_id(50); // the 50 is the length of the string
echo $mybignum;
?>

laura2k

12:37 pm on Dec 11, 2003 (gmt 0)



thanx jatar_k

laura2k

12:52 pm on Dec 11, 2003 (gmt 0)



Worked a treat, is there anyway i can actually make the output into all UPPERCASE?

dcrombie

2:37 pm on Dec 11, 2003 (gmt 0)



Here's one I use:

<?PHP
$str1 = "ABCDEFGHJKLMNPQRSTUVWXYZ";
$str2 = "1234567890";

srand (time());
$split = rand (2, 4);

$id = "";
for ($i=1; $i <= 6; $i++) {
$tmp = ($i <= $split)? $str1 : $str2;
$pos = rand (0, strlen ($tmp)-1);
$id .= substr ($tmp, $pos, 1);
}
?>

It creates a 6-character string starting with 2-4 characters from $str1 followed by characters from $str2.

jatar_k

5:35 pm on Dec 11, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



instead of
echo $mybignum;

just try
echo strtoupper [ca.php.net]($mybignum);