how to generate unique referral code in php

Viewed 8683


I have created E-commerce website, In user system, I created referral system works like this -> When a visitor create an account then unique referral code for that customer will be generated. I fear that referral code should not be matched when I'll have a lot of users. So, I wanna create unique referral code. I am creating like this:

$referral_code = strtolower(substr($first_name,0,3)).$this->refer_code(3);

public function refer_code($limit){
    return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
}

Here, I am picking first 3 letters from user name and 3 random letters. It's generating referral code like this:

illqhx

But my boss said that It's very difficult to read and tell to other. So, he wants that referral code should be only numbers or 3 letters from name and 3 numbers should be generated automatically and it should be unique, and limit should be 5 or 6.
Please help me

4 Answers

Try this

function random_strings($length_of_string) 
{ 
    $str_result = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz'; 
    return substr(str_shuffle($str_result), 0, $length_of_string); 
} 

// This function will generate 
// Random string of length 10 
echo random_strings(10); 

?> 

I recommend adding something like the following to your User class. You can use createReferralCode from the outside to retrieve the code. It will always return the same value. You could also just return $this and use an accessor method to retrieve the value.

How you save or validate your new key I'm leaving up to you.

/**
 * Referral Code
 *
 * @var string
 */
protected $referralCode;

/**
 * Create a referral code and store it on the User.
 *
 * @return string
 */
public function createReferralCode() : string
{
    if (empty($this->referralCode)) {
        // attempt to create a referral code until the one you have is unique
        do {
            $referralCode = $this->generateReferralCode();
        } while (!$this->hasUniqueReferralCode($referralCode));

        $this->referralCode = $referralCode;
    }

    return $this->referralCode;
}

/**
 * Generate a referral code.
 *
 * @return string
 */
protected function generateReferralCode() : string
{
    // generate crypto secure byte string
    $bytes = random_bytes(8);

    // convert to alphanumeric (also with =, + and /) string
    $encoded = base64_encode($bytes);

    // remove the chars we don't want
    $stripped = str_replace(['=', '+', '/'], '', $encoded);

    // get the prefix from the user name
    $prefix = strtolower(substr($this->firstName, 0, 3));

    // format the final referral code
    return ($prefix . $stripped);
}

/**
 * Check if the referral code is unique.
 *
 * @param  string  $referralCode
 *
 * @return boolean
 */
protected function hasUniqueReferralCode(string $referralCode) : bool
{
    // check against database to enforce uniqueness
}
if($referrelid){
    $condition = ' AND username LIKE "' . $referrelid. '" ';
    $sql = $db->getRecFrmQry("SELECT ewallet FROM " . DB_TBLPREFIX . "_mbrs WHERE 1 " . $condition . "");
    $ewallet = $sql[0]['ewallet'] + 50;
    $data =array(
        'ewallet' => $ewallet,
    );
    if (count($sql) > 0) {
         $update = $db->update(DB_TBLPREFIX . '_mbrs', $data, array('username' => $referrelid));
    }
}

When the new user creates an account with any refferel id, $50 added to his account when the account is created successfully.

If you want your referrer code to be only numbers, perhaps generating a unique code is not the best idea. Instead you can save the code in a database, start from 000001 and work your way up.

In this case you're guaranteed to have unique codes since you know all the previous codes.

This could also work with alphanumeric characters using the same principle. But starting with 000AAA or something similar.

Leaving aside the guaranteed non collision you can also keep track of issued referrer codes and invalidate them at will using a column such as is_active.


Concrete example from your code:

Lets assume that client Dave has referrer code illqhx. Lets also assume that client Linda wants a referrer code too.

Your code may look something like this:

// get dave's referrer code from the database
$dave_referrer_code = 'illqhx';
$linda_referrer_code = $dave_referrer_code++;
var_dump($dave_referrer_code); // illqhx
var_dump($linda_referrer_code); // illqhz

// Do note that this code won't work, it's just an example

What you should actually do is get the column with the largest id from the database, get the referrer code from there and increment that.

Having a unique index on the referrer_code column will guaranteed uniqueness since you can't have duplicate codes.

It makes much easier as far as I'm concerned.

Related