-1

I have to generate a random code in PHP and save it in MySQL but this code must be unique, I'm new in .php and I know this isn't a place where people just ask for done things. I promisse this is the first and last time I ask for done things here and I will study and understand that code. Thank you so much.

I got this:

    <?php
function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
    $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
    $rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd >= $range);
return $min + $rnd;
}

function getToken($length)
{
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    $max = strlen($codeAlphabet) - 1;
    for ($i=0; $i < $length; $i++) {
        $token .= $codeAlphabet[crypto_rand_secure(0, $max)];
    }
    return $token;
}

But I don't know how to check if that code is unique in Mysql before save in a table

Lucas Ferraz
  • 620
  • 1
  • 7
  • 12
  • why not just use an AI'd column? and can set columns as UNIQUE. why do you use that code for? edit: ah, for random passwords(?). if so, why? – Funk Forty Niner Feb 18 '16 at 15:16
  • Why not use `password_hash` http://php.net/manual/en/function.password-hash.php it generates random passwords that can be used to authenticate against – Bloafer Feb 18 '16 at 15:22
  • ok, this smells like it's going to be an "answers only" type of question where a response will only be given for answers and not comments. Take it up with the guy's answer below. Can't guarantee it's going to work for you though. Edit: Yep, I was right. – Funk Forty Niner Feb 18 '16 at 15:25
  • Thanks to Snowboard404, now I just have to check if it exists in Mysql. Thank you guys – Lucas Ferraz Feb 18 '16 at 15:29

1 Answers1

1

A good description of how to do this can be found here: PHP: How to generate a random, unique, alphanumeric string?

See the answer down further in the page from Scott if it is crucial for the security of the application for it to be unique: https://stackoverflow.com/a/13733588/2224584

Community
  • 1
  • 1
Wes
  • 866
  • 10
  • 19