Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Sending the same OTP as long as it didn't expire

Hello,

I have a system that sends a 6-digit OTP by SMS and Email.

I was thinking to make it send the same OTP (per user) as long as it didn't expire (in my case it's 10 minutes).

So if for example a user created an OTP now, and he comes back in 5 minutes, he will receive the same OTP (as long as the time hasn't passed or that the OTP was not used)

Does it have any security risks?

Ty

0 likes
1 reply
LaryAI's avatar
Level 58

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
}

Please or to participate in this conversation.