Sending the same OTP as long as it didn't expire can have security risks. If an attacker intercepts the OTP, they can use it to gain access to the user's account even after the OTP has expired. It's better to generate a new OTP every time the user requests one.
However, if you still want to implement this feature, you can store the OTP and its expiration time in the database. When a user requests an OTP, check if there is an unexpired OTP for that user in the database. If there is, send the same OTP. If not, generate a new OTP and store it in the database with the current time as the expiration time.
Here's an example implementation in PHP:
// Generate a new OTP
function generateOTP() {
return rand(100000, 999999);
}
// Check if there is an unexpired OTP for the user
function getUnexpiredOTP($userId) {
$otp = DB::table('otp')
->where('user_id', $userId)
->where('expires_at', '>', now())
->first();
return $otp ? $otp->code : null;
}
// Send the OTP to the user
function sendOTP($userId) {
$otp = getUnexpiredOTP($userId);
if (!$otp) {
$otp = generateOTP();
DB::table('otp')->insert([
'user_id' => $userId,
'code' => $otp,
'expires_at' => now()->addMinutes(10),
]);
}
// Send the OTP by SMS and Email
}