Email verification is a crucial security feature for modern web applications. In this tutorial, I'll guide you through creating a robust OTP (One-Time Password) verification system using PHPMailer. Users will submit a form with their email, receive a unique OTP code via email, and then verify their email by entering that code.
What is PHPMailer?
PHPMailer is a powerful, feature-rich library for sending emails from PHP applications. It provides a simple interface for sending mail with attachments, HTML content, and using various protocols including SMTP, which we'll be using in this tutorial.
Setting Up Your OTP Email System
Let's break down the process of creating an email verification system with OTP in several clear steps.
Step 1: Download PHPMailer
First, download PHPMailer from GitHub. You can clone the repository or download it as a ZIP file and extract it into your project directory.
Step 2: Create Your HTML Form
Create an HTML form where users can input their email address to receive the OTP code:
<form action="send_email.php" method="post"> <label for="email">Your Email:</label> <input type="email" id="email" name="email" required><br> <button type="submit">Send Email</button> </form>
Step 3: Include PHPMailer in Your Project
Include PHPMailer in your project by requiring its necessary files in your PHP script:
<?php require 'phpmailer/src/PHPMailer.php'; require 'phpmailer/src/SMTP.php'; require 'phpmailer/src/Exception.php'; ?>
Step 4: Configure PHPMailer
Configure PHPMailer to use your Gmail account to send emails. You'll need to replace '[email protected]' and 'your-app-password' with your own email and app password.
Important: For security reasons, Google requires you to use an app password rather than your regular Gmail password. You can create an app password by visiting Google App Passwords.
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = '[email protected]'; $mail->Password = 'your-app-password'; $mail->SMTPSecure = 'ssl'; $mail->Port = 465; ?>
Step 5: Send OTP Email
Create a PHP script (send_email.php) that generates a random OTP and sends it to the user's email:
<?php session_start(); // Import PHPMailer classes into the global namespace use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // Required files require 'phpmailer/src/Exception.php'; require 'phpmailer/src/PHPMailer.php'; require 'phpmailer/src/SMTP.php'; // Generate OTP $otp = mt_rand(100000, 999999); // Create an instance; passing `true` enables exceptions $mail = new PHPMailer(true); // Server settings $mail->isSMTP(); // Send using SMTP $mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '[email protected]'; // SMTP write your email $mail->Password = 'your-app-password'; // SMTP password $mail->SMTPSecure = 'ssl'; // Enable implicit SSL encryption $mail->Port = 465; // Recipients $mail->setFrom('[email protected]', 'Your Name'); // Sender Email and name $mail->addAddress($_POST['email']); // Assuming email is submitted via POST $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Your OTP for Verification'; $mail->Body = 'Your OTP is: ' . $otp; // Success sent message alert try { // Attempt to send the email $mail->send(); $_SESSION['otp'] = $otp; // Redirect to otp_confirm.php if OTP is sent successfully echo " <script> document.location.href = 'otp_confirm.php'; </script> "; } catch (Exception $e) { // Display an error message if sending the OTP fails unset($_SESSION['otp']); echo " <script> alert('Sending OTP failed. Please try again later.'); document.location.href = 'signup.php'; </script> "; } ?>
Step 6: Verify OTP
Create the otp_confirm.php file where users will enter the OTP they received via email:
<?php session_start(); if ($_SERVER["REQUEST_METHOD"] == "POST") { $user_otp = $_POST['otp']; $otp = $_SESSION['otp']; if ($user_otp == $otp) { unset($_SESSION['otp']); header('Location: create_password.php'); exit(); } else { echo '<script>alert("Incorrect OTP. Please try again.");</script>'; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Verify OTP</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <style> .logo { max-width: 60%; } input.form-control.bg-light { padding: 12px; font-size: 16px; height: 7vh; border: none; border-radius: 0; box-shadow: none; background-color: #f8f9fa; color: #495057; } input.form-control.bg-light:focus { background-color: #e9ecef; } .eye-icon { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; } </style> </head> <body> <div class="container"> <br> <a href="signup.php" class="btn arrow"><img src="image/arrow.png" alt="" style="height:5vh"></a> <div class="row justify-content-center mt-5"> <div class="col-md-8 col-lg-6 text-center"> <img src="image/logo1.png" alt="Logo" class="img-fluid mb-2 logo"> <h3 class="mb-4"><strong>Confirm OTP</strong></h3> </div> </div> <p class="text-center mt-3" style="color:#828282">Enter the OTP <br> to be a part of Roomsineverest</p><br> <div class="row justify-content-center"> <div class="col-md-6 col-lg-4"> <form action="" method="POST"> <div class="form-group position-relative"> <input type="text" class="form-control bg-light" id="otp" name="otp" placeholder="Enter 6 digit code"> </div> <button type="submit" class="btn btn-block text-white font-weight-bold" style="background:#092C4C">Continue</button> </form> <br> <a href=""><button class="btn btn-block font-weight-bold" style="background:none;color:blue">Resend</button></a> </div> </div> </div> </body> </html>
Security Considerations
When implementing OTP verification systems, keep these security considerations in mind:
- OTP Expiration: Set a time limit for OTP validity (typically 5-15 minutes).
- Rate Limiting: Limit the number of OTP requests from a single IP address to prevent abuse.
- OTP Length: Use a minimum of 6 digits for reasonable security.
- Secure Storage: Store the OTP securely in the session or database.
- HTTPS: Always use HTTPS for the entire authentication process.
Conclusion
Email verification with OTP adds an important layer of security to your application by confirming that users have access to the email addresses they provide. This implementation using PHPMailer is straightforward and can be customized to fit your specific requirements.
For more advanced implementations, consider adding features like OTP expiration, multiple delivery methods (SMS, email), and integration with your user management system.