How to create a unique random string in PHP with check MySQL

When building web software applications I sometimes need a way to generate unique random strings. Unique random strings can be used as character keys or tokens to identify database records without having to give away the database records ID number. I personally use unique random strings to produce clickable links in my “Request lost password” emails. The unique random string can be matched to a user record and the password can be re-created and sent to the user.

define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "student");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);

function refercode()
{
	$string = '';
	$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	$max = strlen($characters) - 1;
	for ($i = 0; $i < 6; $i++) {
		$string .= $characters[mt_rand(0, $max)];
	}
	$refer = "select * from user_detail where refer_code = '".$string."' ";
	$coderefertest = mysqli_query($con,$refer);

	if(mysqli_num_rows($coderefertest)>0)
	{
		return refercode();
	}
	else
	{
		return $string;
	}
}
$refer_by = refercode();

Leave a Reply

Your email address will not be published. Required fields are marked *