Tuesday, March 1, 2022

[FIXED] Creating a 14 character 'random key generator'

Issue

I'm trying to use CodeIgniter to write up a small program for school which generates a random 'key' every time I click the 'generate' button. Looking to see if there's a way for me to create a function where I can fill up a 14 character array with a random number or letter and then set the array to a variable which I can call upon to display as my generated key.

Any and all help would be much appreciated as I am new to CodeIgniter.


Solution

A while back I wrote this function in PHP, it does what it does and gives you some flexibility as well through complexity modifiers, I used a default set of 5 different 'levels' of characters and the length is also variable ofcourse.

I'm just going to chuck it in here and 'try' to explain what is going on as well as I can by comments:

function rsg($length = 10, $complexity = 2) {
        //available 'complexity' subsets of characters
        $charSubSets = array(
            'abcdefghijklmnopqrstuvwxyz',
            'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            '0123456789',
            '!@#$%^&*()_+{}|:">?<[]\\\';,.`~',
            'µñ©æáßðøäåé®þüúíóö'
        );

        // will be filled with subsets from above $charSubsets
        $chars = '';

        //concact each subset until complexity is reached onto the $chars variable
        for ($i = 0; $i < $complexity; $i++)
            $chars .= $charSubSets[$i];

        //create array containing a single char per entry from the combined subset in the $chars variable.
        $chars = str_split($chars);
        //define length of array for mt_rand limit
        $charCount = (count($chars) - 1);
        //create string to return
        $string = '';
        //idk why I used a while but it won't really hurt you when the string is less than 100000 chars long ;)
        $i = 0;
        while ($i < $length) {
            $randomNumber = mt_rand(0, $charCount); //generate number within array index range
            $string .= $chars[$randomNumber]; //get that character out of the array
            $i++; //increment counter
        }

        return $string; //return string created from random characters
    }

This is what I currently use and it has satisfied my needs for quite some time now, if anyone reading over this has improvements I'd love to hear them as well!



Answered By - SidOfc

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.