-1

I am trying to implement OTP Verification in a Signup form Via PHP the thing is that I don't want to save the user's data unless they have verified their Email for the sake of saving the Database's Bandwidth but the Problem is that if I will not save the user's Data in the database how will I be able to verify their Email?

Any thoughts on that?

Thanks

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Shayan Kanwal
  • 542
  • 4
  • 15
  • 1
    Store the generated OTP inside the session and compare the user input to that session variable – Moudi Dec 18 '22 at 08:49
  • @Moudi Thanks for your answer its a really Good Idea Thanks! Please post that in the answer format so I can upvote it! – Shayan Kanwal Dec 18 '22 at 08:55
  • 1
    Sure thing, just remember that sessions are stored server side, so it should be generally safe to use it to store data you don't want the user to see. The opposite of that is cookies, which is stored on the user side. – Moudi Dec 18 '22 at 08:58
  • Many a times, user data is saved regardless of verification for no. of active/inactive members and also for many other metrics. – nice_dev Dec 18 '22 at 09:03
  • 2
    I agree with @nice_dev, you're saving an integer, which shouldn't take up much bandwidth. It wouldn't hurt to store it in the database, and it will allow you to verify across multiple devices (send verification URL to their email as an example) – Moudi Dec 18 '22 at 09:05

1 Answers1

1

Here's a rough example, you will need to edit it to fit your project obviously. Maybe you're submitting to a different script, ask for email from a different script, etc.

You can leverage the session to store data temporarily.

session_start();



echo '<form action="" method="post">
    <input type="text" name="otp" />
    <input type="submit" value="Submit" />
</form>';

// if the form is submitted, then check for OTP, otherwise generate it and store it in session
if (isset($_POST['otp'])) {
    // check if the OTP is correct
    if ($_POST['otp'] == $_SESSION['otp']) {
        //do something
    } else {
        // do something else
    }
}
else{
    $otp = rand(100000, 999999); //this is not a safe way to generate an OTP, but just for examples sake
    $_SESSION['otp'] = $otp;
    // code that sends the OTP to the user here using mail, text or API... 
    // ...
}
Moudi
  • 525
  • 3
  • 12
  • if you found the question helpful don't forget to upvote the answer! – Shayan Kanwal Dec 18 '22 at 09:51
  • 2
    Do note `rand` shouldn't be used to create a secure random - [see here](https://stackoverflow.com/questions/1182584/secure-random-number-generation-in-php) – DarkBee Dec 18 '22 at 10:25