Send Email Verification And OTP Through PHPMailer
This is the phpMailer explanation of the Login Module.
Installation
Method 1 : Composer
You can use Composer or simply Download the Release. Follow the installation instructions if you do not already have composer installed.
Once composer is installed, execute the following command in your project root to install this library:
composer require phpmailer/phpmailer
If you are downloaded PHPMailer through composer, then remember to include the autoloader to your PHP coding.
require_once 'vendor/autoload.php';
Method 2: Download
Alternatively, if you're not using composer, download the PHPMailer from here and put into path directories specified in your PHP configuration
Finally, Not matter your are using composer or download instead, it is compulsory to include the PHPMailer into you PHP coding
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
Generate Email Verification
Create email verification via PHPMailer for account registration
At registeration.php
registeration.php
Replace the Username
and Password
to your [Email Username] and [App Password].
The way to generate app password refer to generate app password
<?php
// Include phpMailer file
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../phpmailer/src/Exception.php';
require '../phpmailer/src/PHPMailer.php';
require '../phpmailer/src/SMTP.php';
// Email Generation Start ------------------------------------------------------------------------------------------------------------------------
// Function to generate email with PHPMailer
function sendEmail($email, $subject, $body)
{
$mail = new PHPMailer(true);
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->Username = '[email protected]'; // Your gmail
$mail->Password = 'XXX'; // Your app password
$mail->setFrom("[email protected]", "XXXX"); // Your gmail
$mail->addAddress($email);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
if ($mail->send()) {
return true;
} else {
return false;
}
}
// Email Generation End ------------------------------------------------------------------------------------------------------------------------
// Initialise email generated with PHPMailer and send email
function registerUser($conn, $username, $email, $password, $status)
{
$uniqueID = generateUniqueID();
$currentTime = date("Y-m-d H:i:s");
// random code for otp
$code = rand();
// password encryption
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// Construct the SQL query
$sql = "INSERT INTO shifu_login (name, email, password, uniqID, status, code, time) VALUES ('$username', '$email', '$hashedPassword', '$uniqueID', '$status', '$code', '$currentTime')";
// Execute the query
if (mysqli_query($conn, $sql)) {
if ($status == "unverified") {
$subject = "Email Address Verification";
$body = "Please click the <a href=http://localhost:3000/db_action/verify.php?code=" . $code . ">link</a> to verify your email address.";
// Send email
if (sendEmail($email, $subject, $body)) {
$_SESSION["msg_success"] = "Register successfully. Please check your email.";
return true;
} else {
// Check if email fails to send
$_SESSION["msg_error"] = "Email sending failed.";
return false;
}
} else if ($status == "pending") {
$_SESSION["msg_success"] = "Your account was registered and pending approved.";
return true;
}
} else {
// Check if email verification failed
$_SESSION["msg_error"] = "Registeration failed.";
return false;
}
At verify.php
verify.php
verify the code attached at url and find the correct user.
if (isset($_GET['code'])) {
$id = $_GET['code'];
//update the database after verified
$result = getUniqID($id, $conn);
$name = $result['name'];
$uniqID = $result['uniqID'];
$sql = "UPDATE `shifu_login` SET status = 'verified' WHERE code = '$id'";
$result = mysqli_query($conn, $sql);
if ($result) {
$sql2 = "INSERT INTO shifu (name, uniq_id) VALUES (?, ?)";
$stmt2 = mysqli_prepare($conn, $sql2);
if($stmt2){
mysqli_stmt_bind_param($stmt2, "ss", $name, $uniqID);
$result2 = mysqli_stmt_execute($stmt2);
}
$_SESSION['verification_result'] = 'success';
mysqli_stmt_close($stmt2);
} else {
$_SESSION['verification_result'] = 'failed';
}
header("location: ../login.php");
} else {
echo "<script>alert('無法取得代碼! 請再試一次!')</script>";
}
function getUniqID($id, $conn)
{
$sql = "SELECT name, uniqID FROM shifu_login WHERE code = $id ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$name = $row['name'];
$uniqID = $row['uniqID'];
}
} else {
echo "未找到結果。";
}
return array('name' => $name, 'uniqID' => $uniqID);
}
At login.php
login.php
Check verification result to ensure email has been verified
// Check Verification Start ------------------------------------------------------------------------------------------------------------------------
if (isset($_SESSION['verification_result'])) {
if ($_SESSION['verification_result'] === 'success') {
// echo "<script>alert('Your account is verified! You can proceed to login now!')</script>";
echo "<script>alert('Your Account Verified! You can login Now !')</script>";
} elseif ($_SESSION['verification_result'] === 'failed') {
// echo "<script>alert('Email verification failed! Please try again!')</script>";
echo "<script>alert('Verify Failed, Please try again! ')</script>";
}
// Clear the session variable to prevent displaying the message again
unset($_SESSION['verification_result']);
}
\
Forgot Password OTP
Generate OTP code when user forgot password
At forgot.php
forgot.php
Generate random OTP code and store into database.
// OTP Generation Start ------------------------------------------------------------------------------------------------------------------------
// Function to generate OTP code
function generateOTP($conn, $email)
{
//Generate code
$otp = mt_rand(100000, 999999);
$subject = "Here is Your OTP Number!";
$body = "Your OTP Number: " . $otp . " <br>Please avoid sharing your OTP number with anyone else to protect the security of your account.";
//update sql
$sql = "UPDATE shifu_login SET OTP='$otp' WHERE email='$email'";
if (mysqli_query($conn, $sql)) {
//send email with sendEmail() function
if (sendEmail($email, $subject, $body)) {
$_SESSION["email_resetpw"] = $email;
return true;
} else {
return false;
}
} else {
return false;
}
}
At otp_confirm.php
otp_confirm.php
Confirm OTP by retrieving and comparing OTP code stored in database and code entered by user with otp_confirm.php
// Check Confirm OTP Start ------------------------------------------------------------------------------------------------------------------------
// Function to check OTP
function checkotp($conn, $otp)
{
$email = $_SESSION["email_resetpw"];
$query = "SELECT * FROM shifu_login WHERE otp='$otp' AND email='$email'"; //locate email from database
$result = $conn->query($query);
if ($result->num_rows > 0) {
return true;
} else {
$_SESSION["otp_error"] = "that OTP is wrong.";
return false;
}
}
Last updated