0

I need to generate a random 4 character string on each form submission. I got this solution from here.

which is this.

 function genTicketString() {
 return substr(md5(uniqid(mt_rand(), true)), 0, 4);
 }
 add_shortcode('quoteticket', 'genTicketString');

But this mostly generates a similar ID! probably if I can add the date & time along with the 4 character, it will fix it.

So how can I add the data & the time to the generated string?

Community
  • 1
  • 1
Rayan Sp
  • 1,002
  • 7
  • 17
  • 29

2 Answers2

2

As a direct answer to your question

To generate a pseudo random string, you can use this function :

function getPseudoRandomString($length = 4) {
    $base64Chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/';
    $result = '';

    for ($i = 0; $i < $length; ++$i) {
        $result .= $base64Chars[mt_rand(0, strlen($base64Chars) - 1)];
    }

    return $result;
}

NOTE : This generates a pseudo random string, there is no way to be sure the string is unique.


To get a "more unique" string

first, you should use a longer string : 4 chars is really small : there are only 16 million possibilities with a set of 64 chars.

Then, If you want to add more unicity, you can concatenate a random generated string with the result of uniqid('', true) http://php.net/manual/en/function.uniqid.php


To be sure the string has never been generated

The only way to to be sure the string has never been generated is to save all generated strings in a database and when you generate a new string, you have to check if the string already exists in the database to generate a new one if needed.

The generator function will look like

function generateUniqueString()
    do {
        $string = generateString();
    while (is_in_database($string));

    save_in_database($string);
    return $string;
}
ᴄʀᴏᴢᴇᴛ
  • 2,939
  • 26
  • 44
  • in fact, it depends on what you want : if you want a string with very low risk of collisions, you can use the string generator with a length of 30 chars. this way, there will be 1.5×10^54 possible strings and almost no risk of collision. If you absolutely not want possible collisions, you will have to use a database to store generated keys and ensure the new key does not exist. – ᴄʀᴏᴢᴇᴛ Jan 17 '17 at 18:38
0

I used this answer instead with little modifications

function genTicketString() {
$d=date ("d");
$m=date ("m");
$y=date ("Y");
$t=time();
$dmt=$d+$m+$y+$t;    
$ran= rand(0,10000000);
$dmtran= $dmt+$ran;
$un=  uniqid();
$dmtun = $dmt.$un;
$mdun = md5($dmtran.$un);
$sort=substr($mdun, 0, 6); // if you want sort length code.
$sort=strtoupper($sort);
return $sort;
}
add_shortcode('quoteticket', 'genTicketString');
Community
  • 1
  • 1
Rayan Sp
  • 1,002
  • 7
  • 17
  • 29