Random Letters and numbers Need Help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
BrettCarr
Forum Newbie
Posts: 22
Joined: Fri Feb 12, 2010 6:45 pm

Random Letters and numbers Need Help

Post 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
rcrd.ortiz
Forum Newbie
Posts: 11
Joined: Sun Dec 26, 2010 10:46 am

Re: Random Letters and numbers Need Help

Post 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
.
Bind
Forum Contributor
Posts: 102
Joined: Wed Feb 03, 2010 1:22 am

Re: Random Letters and numbers Need Help

Post 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;
    }
?>
Post Reply