Creating a 14 character 'random key generator' - php

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.

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!

$a=array(rand(10000000000000, 99999999999999));
is a quick way to get a 14 digit array.

It depends on how random you want it to be. You could specify all characters you want in a $characters string, then just create a string up to $length, picking a random substring of length 1 from the characters string.
What are the requirements?
Do you want it to be as random as possible (This link might be useful)
Are multiple occurrences of one character allowed in one random string?
Here's an example though: PHP random string generator

Related

Generate Alphanumeric String on PHP

I was trying to make a Alphanumeric string and use it for a unique field in my database , it is not a replacement of the Primary key mind it . The following code is generating a 22 length text but my concern is will it continue to produce unique strings as i might need it for unique identification of the data.
<?php
$len =22;
$rand = substr(str_shuffle(md5(time())),0,$len);
echo $rand;
?>
Use openssl_random_pseudo_bytes - it will Generate a pseudo-random string of bytes
and the bin2hex() function converts a string of ASCII characters to hexadecimal values
It will provide you secure token
bin2hex(openssl_random_pseudo_bytes($length))
I will always include the time() in the resulting string to make sure it's unique, if first 10 characters are all numerical will be acceptable to you:
$rand = substr(time().str_shuffle(md5(time())),0,$len);
The function str_shuffle(md5(time())) is very unlikely to produce same results within a second.
This is the easiest way aside from manually checking the records of the existence of the random string for uniqueness.
You can use php provided method uniqid().
You can try the following:
$random = 'abcdefghijklmnopqrstuvwxyz0123456789';
$string = '';
for ($i = 0; $i < $string_length; $i++) {
$string .= $random [rand(0, strlen($random ) - 1)];
}
$string_length is the length of your desired string.It will continue giving you unique strings.

Generating unique 6 digit code

I'm generating a 6 digit code from the following characters. These will be used to stamp on stickers.
They will be generated in batches of 10k or less (before printing) and I don't envisage there will ever be more than 1-2 million total (probably much less).
After I generate the batches of codes, I'll check the MySQL database of existing codes to ensure there are no duplicates.
// exclude problem chars: B8G6I1l0OQDS5Z2
$characters = 'ACEFHJKMNPRTUVWXY4937';
$string = '';
for ($i = 0; $i < 6; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
return $string;
Is this a solid approach to generating the code?
How many possible permutations would there be? (6 Digit code from pool of 21 characters). Sorry math isn't my strong point
21^6 = 85766121 possibilities.
Using a DB and storing used values is bad. If you want to fake randomness you can use the following:
Reduce to 19 possible numbers and make use of the fact that groups of order p^k where p is an odd prime are always cyclic.
Take the group of order 7^19, using a generator co-prime to 7^19 (I'll pick 13^11, you can choose anything not divisible by 7).
Then the following works:
$previous = 0;
function generator($previous)
{
$generator = pow(13,11);
$modulus = pow(7,19); //int might be too small
$possibleChars = "ACEFHJKMNPRTUVWXY49";
$previous = ($previous + $generator) % $modulus;
$output='';
$temp = $previous;
for($i = 0; $i < 6; $i++) {
$output += $possibleChars[$temp % 19];
$temp = $temp / 19;
}
return $output;
}
It will cycle through all possible values and look a little random unless they go digging. An even safer alternative would be multiplicative groups but I forget my math already :(
There is a lot of possible combination with or without repetition so your logic would be sufficient
Collision would be frequent because you are using rand see str_shuffle and randomness.
Change rand to mt_rand
Use fast storage like memcached or redis not MySQL when checking
Total Possibility
21 ^ 6 = 85,766,121
85,766,121 should be ok , To add database to this generation try:
Example
$prifix = "stamp.";
$cache = new Memcache();
$cache->addserver("127.0.0.1");
$stamp = myRand(6);
while($cache->get($prifix . $stamp)) {
$stamp = myRand(6);
}
echo $stamp;
Function Used
function myRand($no, $str = "", $chr = 'ACEFHJKMNPRTUVWXY4937') {
$length = strlen($chr);
while($no --) {
$str .= $chr{mt_rand(0, $length- 1)};
}
return $str;
}
as Baba said generating a string on the fly will result in tons of collisions. the closer you will go to 80 millions already generated ones the harder it will became to get an available string
another solution could be to generate all possible combinations once, and store each of them in the database already, with some boolean column field that marks if a row/token is already used or not
then to get one of them
SELECT * FROM tokens WHERE tokenIsUsed = 0 ORDER BY RAND() LIMIT 0,1
and then mark it as already used
UPDATE tokens SET tokenIsUsed = 1 WHERE token = ...
You would have 21 ^ 6 codes = 85 766 121 ~ 85.8 million codes!
To generate them all (which would take some time), look at the selected answer to this question: algorithm that will take numbers or words and find all possible combinations.
I had the same problem, and I found very impressive open source solution:
http://www.hashids.org/php/
You can take and use it, also it's worth it to look in it's source code to understand what's happening under the hood.
Or... you can encode username+datetime in md5 and save to database, this for sure will generate an unique code ;)

Random number/letter value

So I was wonder what are some good/preferred methods for generating a 'hex-like' value in PHP? Preferably, I would want to restrict it to 5 characters long like such: 1e1f7
Currently this is what I am doing:
echo dechex(mt_rand(10000, 99999));
however this gives me values anywhere from 4-5 characters long, and I want to keep it at a consistent 4 or 5.
What are some ways to better generate something like this in PHP? Is there even a built in function?
Note: When I say 'hex-like' I really just mean a random combination of letters and numbers. There does not have to be a restriction on available letters.
Something simple like:
$length = 5;
$string = "";
while ($length > 0) {
$string .= dechex(mt_rand(0,15));
$length -= 1;
}
return $string;
(untested)
Or fix your mt_rand range to: mt_rand(65535, 1048575) (10000-fffff in hex) or if you like tinfoil hats: mt_rand(hexdec("10000"), hexdec("ffffff"))
The advantage of the while-loop approach is that it works for arbitrarily long strings. If you'd want 32 random characters you're well over the integer limit and a single mt_rand will not work.
If you really just want random stuff, I'd propose:
$length = 5;
$string = "";
$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=+!##$%^&*()[]"; // change to whatever characters you want
while ($length > 0) {
$string .= $characters[mt_rand(0,strlen($characters)-1)];
$length -= 1;
}
return $string;
(untested)
echo substr( base64_encode( mt_rand(1000, mt_getrandmax() ), 0, 5);
This uses more of the alphabet due to the base64, but remember that it will include upper and lower case letters along with numbers.
Why all the work sha1 is tested and evenly distributed:
substr(sha1(uniqid('moreentropyhere')),0,5);
I have used this to generate millions and millions of uniq uids for sharding tables, no collisions and remarkably evenly distributed regardless of the length you use...
you can even use binary form of sha1 hash for base 64:
base64_encode(sha1(uniqid('moreentropyhere'), true))
to limit characters, you can use a regex:
substr(preg_replace('~[^a-km-np-z2-9]~','',strtolower(base64_encode(sha1(uniqid(),true)))),0,6)
Here we limited 0,1,l (letter), and o (letter) from the string, trading a little entropy to prevent confusion (and service tickets) during entry for all ages...

generating an sequential five digit alphanumerical ID

General Overview:
The function below spits out a random ID. I'm using this to provide a confirmation alias to identify a record. However, I've had to check for collision(however unlikely), because we are only using a five digit length. With the allowed characters listed below, it comes out to about 33 million plus combinations. Eventually we will get to five million or so records so collision becomes an issue.
The Problem:
Checking for dupe aliases is inefficient and resource heavy. Five million records is a lot to search through. Especially when this search is being conducted concurrently by different users.
My Question:
Is there a way to 'auto increment' the combinations allowed by this function? Meaning I only have to search for the last record's alias and move on to the next combination?
Acknowledged Limitations:
I realize the code would be vastly different than the function below. I also realize that mysql has an auto increment feature for numerical IDs, but the project is requiring a five digit alias with the allowed characters of '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'. My hands are tied on that issue.
My Current Function:
public function random_id_gen($length)
{
$characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
$max = strlen($characters) - 1;
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
return $string;
}
Why not just create a unique index on the alias column?
CREATE UNIQUE INDEX uniq_alias ON MyTable(alias);
at which point you can try your insert/update and if it returns an error, generate a new alias and try again.
What you really need to do is convert from base 10 to base strlen($characters).
PHP comes with a built in base_convert function, but it doesn't do exactly what you want as it will use the numbers zero, one and the letter 'o', which you don't have in your version. So you'll need a function to map the values from base_convert from/to your values:
function map_basing($number, $from_characters, $to_characters) {
if ( strlen($from_characters) != strlen($to_characters)) {
// ERROR!
}
$mapped = '';
foreach( $ch in $number ) {
$pos = strpos($from_characters, $ch);
if ( $pos !== false ) {
$mapped .= $to_characters[$pos];
} else {
// ERROR!
}
}
return $mapped;
}
Now that you have that:
public function next_id($last_id)
{
$my_characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
$std_characters ='0123456789abcdefghijklmnopqrstuv';
// Map from your basing to the standard basing.
$mapped = map_basing($last_id, $my_characters, $std_characters);
// Convert to base 10 integer and increment.
$intval = base_convert($mapped, strlen($my_characters), 10);
$intval++;
// Convert to standard basing, then to our custom basing.
$newval_std = base_convert($intval, 10, strlen($my_characters));
$newval = map_basing($newval_std, $std_characters, $my_characters);
return $newval;
}
Might be some syntax errors in there, but you should get the gist of it.
You could roll your own auto-increment. It would probably be fairly inefficient though as you'd have to figure out where in the process your increment was. For instance, if you assigned the position in your random string as an integer and started with (0)(0)(0)(0)(0) that would equate to 22222 as the ID. Then to get the next one, just increment the last value to (0)(0)(0)(0)(1) which would translate into 22223. If the last one gets to your string length, then make it 0 and increment the second to last, etc... It's not exactly random, but it would be incremented and unique.

PHP - Unique hashing function thats only 4 digits (doesnt need to be exact)

I'm building a simple URL shortening script, I want to hash the URL to serve as a unique id but if I used something like MD5 the URL wouldn't be very short.
Is their some hashing functions or anyway to create a unique ID thats only 4 or 5 digits long?
Use auto incrementing integers and convert them into identifiers consisting of all letters (lower & uppercase) to shorten them:
function ShortURL($integer, $chr='abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
// the $chr has all the characters you want to use in the url's;
$base = strlen($chr);
// number of characters = base
$string = '';
do {
// start looping through the integer and getting the remainders using the base
$remainder = $integer % $base;
// replace that remainder with the corresponding the $chr using the index
$string .= $chr[$remainder];
// reduce the integer with the remainder and divide the sum with the base
$integer = ($integer - $remainder) / $base;
} while($integer > 0);
// continue doing that until integer reaches 0;
return $string;
}
and the corresponding function to get them back to integers:
function LongURL($string, $chr='abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
// this is just reversing everything that was done in the other function, one important thing to note is to use the same $chr as you did in the ShortURL
$array = array_flip(str_split($chr));
$base = strlen($chr);
$integer = 0;
$length = strlen($string);
for($c = 0; $c < $length; ++$c) {
$integer += $array[$string[$c]] * pow($base, $length - $c - 1);
}
return $integer;
}
Hashing will cause collisions. Just use an autoincrementing value. This includes using alphanumeric characters too to compress it. That is how most URL shortners work.
niklas's answer below is wonderfully done.
The advantage of using MD5 (or equivalent methods) is that the number of possibilities is so large that you can, for all practical purposes, assume that the value is unique. To ensure that a 4-digit random-like ID is unique would require a database to track existing IDs.
Essentially you have to repeatedly generate IDs and check against the DB.
You could always just keep the first 5 characters of a MD5 and if it already exists you add a random value to the url-string and retry until you get a unique one.
I just copied the code and ran it, and it appears that he string function are backwards. I entered the number generated in the shorturl and ran it back thought and got a different number. So I decoded the number and found the string has to be fed back into long url in reverse with the current coding above.

Categories