Generate Verification Key

While registering with a website we often need to verfy our email id. Given below is the code to develop that functionality. The following will generate the verification key which has 6 characters

function generatePassword()
    $length =6;
    $validchars = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    $password ="";
    $counter = 0;

    while($counter < $length)
        $actChar = substr($validchars, rand(0, strlen($validchars)), 1);

        if(!strstr($password, $actchar))
           $password .= $actChar;

   return $password;

rand(0, stlen($validchars)) – generates a random number between 0 and the length of $validchars (inclusive of both ends).

substr($a, $b , len) – get generates a sub string from $a from the first occurrence of $b to length specified by len.

strstr($a, $b) – checks whether $a has $b in it. This is done to create unique characters.

So this is how you generate random string. How you can use it for verification purpose of a user registration is explained in the subsequent posts.


3 thoughts on “Generate Verification Key

  1. What programming language is this, PHP? I was about to write a couple of ways to make it more Perlish, before I realized it wasn’t Perl!

    BTW, your check to avoid duplicated chars actually reduces the randomness of these verification keys.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s