Reputation: 6986
I am creating an application at the moment that needs to give the user a unique 8 digit code (numbers only) that they can enter to access restricted parts of my website, think of it as a rudimentary auth, i.e enter the passcode, the passcode matches a user, the user is returned. What I am having trouble with is creating a unique 8 digit code. I know PHP has uniqid()
but that returns a string that is too long.
I have thought about creating a hash of time()
and the users IP address, but laravel's Hash::create
returns integers and chars.
Can anyone point in the direction of creating a random 8 digit code? I have also tried mt_rand
but obvioulsy there is the chance that this could create matching digits, unless of course I check the database for the code before saving and re-generate if it exists?
Upvotes: 1
Views: 5127
Reputation: 1093
Try this function For Laravel it will return 8 digit number with check unique in db also.
In Controller Function
$expense_id = Expense::get_random_string();
Modal
public static function get_random_string()
{
if (function_exists('com_create_guid') === true)
{
return trim(com_create_guid(), '{}');
}
$random_unique = sprintf('%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
$expense = Expense::where('expense_id', '=', $random_unique)->first();
if ($expense != null) {
$random_unique = $this->get_random_string();
}
return $random_unique;
}
Upvotes: 0
Reputation: 71
rand(10000000, 99999999);
You have 1/89999999 chance to fall on the same number, so you can check if it has already been used or not ;)
Upvotes: 0
Reputation: 344
You need to check-in DB if the number exists or not
$randnum = rand(11111111,99999999);
This will generate a random 8 digit number
Upvotes: 0
Reputation: 571
My suggestion is a do-while loop, this case if the random string already exists it would generate a new one. Generate the code however you want but Laravel actually has a helper (str_random()
) to handle this if you wanted.
/**
* Create a unique code
*
* @return string;
*/
if ( ! function_exists('generateUniqueCode')) {
function generateUniqueCode()
{
do {
$unique_code = str_random(12);
} while (\App\User::where('code', $unique_code)->count() > 0);
return $unique_code;
}
}
Upvotes: 1
Reputation: 5731
This is my code to generate random number :
public function generateRandomNumber($length = 8)
{
$random = "";
srand((double) microtime() * 1000000);
$data = "123456123456789071234567890890";
// $data .= "aBCdefghijklmn123opq45rs67tuv89wxyz"; // if you need alphabatic also
for ($i = 0; $i < $length; $i++) {
$random .= substr($data, (rand() % (strlen($data))), 1);
}
return $random;
}
Upvotes: 1