Page 1 of 1

Random Letters and numbers Need Help

Posted: Sun Dec 26, 2010 4:23 pm
by BrettCarr
I'm trying to create my own password generator but i can't get this to work

Code: Select all

<?php

    $lenght = 10;
    $charactors = "ABCDEFGHIJKLMNOPQRSTUVXXYZ123465789";
    $string = "";
    for($i = 0; $i < $lenght; $i++)
    {
       //why is this not working here?? im lost
        $string .= $charactors[mt_rand(0, strlen($charactors))];
    }
    return $string;
//just trying to see output
 echo "$string";
?>
any help would be great

Re: Random Letters and numbers Need Help

Posted: Sun Dec 26, 2010 4:32 pm
by rcrd.ortiz
Hi, well first of all you have a return statement so the script never makes it to

Code: Select all

echo "$string"
.
Second, the possibility of an array index offset exists inside the for loop if you try to access the strlen( $charactors ) element of the array since the last array index would be

Code: Select all

strlen($charactors) - 1
.

Re: Random Letters and numbers Need Help

Posted: Mon Dec 27, 2010 9:26 am
by Bind

Code: Select all

<?php
function CreateRandomString($instances,$min_length,$max_length)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQUSTUVWXYZ";
        srand((double)microtime()*1000000);
        global $strings;
        $strings = Array();
        for ($inst=0;$inst<$instances;$inst++)
            {
                $i = 0;
                $pass = '';
                $randlength = rand($min_length,$max_length);
                while ($i < $randlength)
                    {
                        $num = rand(0,strlen($chars));
                        $tmp = substr($chars, $num, 1);
                        $pass = $pass . $tmp;
                        $i++;
                    }
                $strings[$inst] = $pass;
            }
        return $strings;
    }
?>