Email OTP Verification using PHP in Live Server
Last Updated :
26 Jul, 2024
The task is to create and design a sign-up and login form. In the sign-up form, the user will sign-up with a custom username and password and a valid email then the user will receive an OTP through the email, and after successful verification of OTP user account will be created and data will be stored in MySQL database, and then the user will be redirected to the home page. In the login form, the user can login with the username and password that the user entered while creating the new account.
Note: We will implement this whole thing in a live server, anyone can implement this to their own local server like XAMPP, but the email verification part will not work in the local server.
Approach for Sign-up Form:
- The first task is to create a MySQL server Database and a Table according to our requirements.
- We connect our MySQL server Database using PHP mysqli_connect() function that takes four arguments, i.e. our “servername”, “username”, “password” and “database”.
- After entering all the details of the user, we will generate a 6 digit random number using PHP rand() function and store it to the local session variable then send it to the user email using PHP mailer function.
- When the user enters the OTP, we will verify it with the OTP stored in session if these match then store redirect the user to the home page.
- Create a new table with the name as username the user provided to store the email and password of that user.
Approach for Log-in Form:
- Connect to the database as described above, then check the credential provided by the user, if they match with the data stored in the database then redirect the user to the home page else show the related error.
PHP code for registration form: register.php
PHP
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
$otp=$_SESSION["OTP"];
if(isset($_SESSION["logged-in"])){
header("Location:profile.php");
}
$username="sign up";
$login_btn="Login";
if(isset($_SESSION["username"])){
$username=$_SESSION["username"];
$login_btn="Logout";
}
if($_SERVER["REQUEST_METHOD"]=="POST"){
$con=mysqli_connect('localhost',
'database_username',
'database_pass','database_name');
if(!$con)
echo ("failed to connect to database");
$username1=$_POST['username'];
$prefix="_";
$username=$prefix.$username1;
$password=$_POST['Password'];
$repassword=$_POST['RePassword'];
$email1=$_POST['Email'];
$email=strval($email1);
if($password!=$repassword){
echo("<script>alert('password not matches')</script>");
}
else{
if(strlen($password)<8){
echo(
"<script>alert('password length must be atleast 8')</script>");
}
else{
$query="insert into 1_user(username,email,password)
values('$username','$email','$password')";
$sql = "SELECT id,username, password FROM 1_user";
$result = $con->query($sql);
$username_already_exist=false;
$email_already_exist=false;
// Checking if user already exist
if(($result->num_rows)> 0){
while($row = $result->fetch_assoc()) {
// echo "<br> id: " . $row["id"] .
" - username= " . $row["username"] .
" password= " . $row["password"] . "<br>";
if($row["username"]==$username){
$username_already_exist=true;
break;
}
if($row["email"]==$email){
$email_already_exist=true;
break;
}
}
}
// echo($ok);
if($username_already_exist==false){
// This is my hosting mail
$from ="[email protected]";
$to=$email;
$subject="verify-account-otp";
// Generating otp with php rand variable
$otp=rand(100000,999999);
$message=strval($otp);
$headers="From:" .$from;
if(mail($to,$subject,$message,$headers)){
$_SESSION["username"]=$username;
$_SESSION["OTP"]=$otp;
$_SESSION["Email"]=$email;
$_SESSION["Password"]=$password;
$_SESSION["registration-going-on"]="1";
header("Location:verify-otp.php");
}
else
echo("mail send faild");
}
else{
echo(
"<script>alert('username already taken')</script>");
}
}
}
}
?>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css"
href="css/style.css" media="screen" />
<!-- adding bootstrap -->
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity=
"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity=
"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous">
</script>
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous">
</script>
<div class="nav-bar">
<div class="title">
<h3>welcome to my website</h3>
</div>
</div>
</head>
<body>
<form class="form-register"
action="register.php" method="POST">
<div class="form-group">
<label>username</label>
<input type="text" class="form-control"
name="username" id="username"
aria-describedby="emailHelp"
placeholder="username" required>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control"
name="Email" id="Email"
placeholder="Email" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control"
name="Password" id="Password"
placeholder="Password" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password"
class="form-control" name="RePassword"
id="RePassword" placeholder="RePassword"
required>
</div>
<button type="submit"
class="btn btn-primary btn-lg">
Register
</button>
<button type="button"
class="btn btn-warning btn-lg"
id="login-button">
Already Registered
</button>
</form>
<script>
$("#login-button").click(function () {
window.location.replace("index.php");
});
</script>
</body>
</html>

PHP code to send and verify OTP: verify-otp.php
PHP
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
// Retrieving otp with session variable
$otp=$_SESSION["OTP"];
?>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css"
href="css/style.css" media="screen" />
<!-- Adding bootstrap -->
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity=
"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity=
"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous">
</script>
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous">
</script>
<div class="nav-bar">
<div class="title">
<h3>welcome to my website</h3>
</div>
</div>
</head>
<body>
<form class="form-login">
<div class="form-group">
<input type="text" class="form-control"
name="otp" id="OTP"
aria-describedby="emailHelp"
placeholder="Enter OTP" required>
</div>
<button type="button"
class="btn btn-primary btn-lg"
id="verify-otp">
verify otp
</button>
</form>
<script>
$("#resend-otp").click(function () {
window.location.replace("resend-otp.php");
});
$("#verify-otp").click(function () {
// window.location.replace("index.php");
var otp1 = document.getElementById("OTP").value;
// alert(otp1);
var otp2 = ("<?php echo($otp)?>");
// alert(otp2);
if (otp1 == otp2) {
window.location.replace("logged-in.php");
}
else {
alert("otp not matches")
}
});
</script>
</body>
</html>

PHP code to resend OTP in case of OTP not received: resend-otp.php
PHP
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
// ini_set('dispaly_errors',1);
// error_reporting(E_ALL);
$from ="[email protected]";
$to=$_SESSION["Email"];
$subject="verify-account-otp";
$otp=rand(100000,999999);
$message=strval($otp);
$headers="From:" .$from;
if(mail($to,$subject,$message,$headers)){
$_SESSION["OTP"]=$otp;
header("Location:verify-otp.php");
}
else
echo("mail send faild");
?>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css"
href="css/style.css" media="screen" />
<!-- Adding bootstrap -->
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity=
"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity=
"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous">
</script>
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous">
</script>
<div class="nav-bar">
<div class="title">
<h3>welcome to coer library</h3>
</div>
</div>
</head>
<body>
<div class="form">
<form action="register.php" method="POST">
<label><b>Register To MY website</b></label>
<hr class="first">
<label><b>Coer-ID</b></label>
<input type="text" name="Coer-ID"
placeholder="Coer-ID" required id="Coer-ID"
class="float-left1">
<br><br>
<label><b>Email</b></label>
<input type="email" name="Email"
placeholder="Email" required id="Email"
class="float-left1">
<br><br>
<label><b>Password </b> </label>
<input type="Password" name="Password"
placeholder="Password" required id="Password"
class="float-left1">
<br><br>
<label><b>RePassword </b> </label>
<input type="Password" name="RePassword"
placeholder=" Re Type Password"
required id="Repassword"
class="float-left1">
<br><br>
<button type="submit" name="login"
value="login" id="register-button">
create account
</button>
<br><br>
</form>
</div>
</body>
</html>
After successful OTP verification inserting user data to table 1_user:
Table schema, each row has these 4 columns:
id (int data type as primary key)
username (text data type)
email (text data type)
password (text data type)


PHP code for login form also the default page: index.php
PHP
<!DOCTYPE html>
<html lang="en">
<?php
$message=
"logged in successfully...redirecting to home page";
session_start();
if(isset($_SESSION["logged_in"])){
header("Location:profile.php");
}
if($_SERVER["REQUEST_METHOD"]=="POST"){
$con=mysqli_connect('localhost',
'database_username',
'database_pass','database_name');
if($con);
else
echo "failed to connect to database";
$username1=$_POST['username'];
$prefix="_";
$username=$prefix.$username1;
$password=$_POST['Password'];
$sql = "SELECT id,username, password FROM 1_user";
$result = $con->query($sql);
if ($result->num_rows > 0) {
$fnd=0;
while($row = $result->fetch_assoc()) {
/* echo "<br> id: ". $row["id"].
" - username= ". $row["username"].
" password= " . $row["password"] . "<br>"; */
if($row["username"]==$username and
$row["password"]==$password) {
$_SESSION["username"] = $username;
$_SESSION["registration-going-on"]="0";
$fnd=1;
$_SESSION["logged_in"]="1";
echo '<div class="alert alert-success"
role="alert">'.$message.'</div>';
echo
"<script>setTimeout(\"location.href = 'profile.php';\",3000);</script>";
}
}
if($fnd==0)
echo(
"<script>alert('username password not matches')</script>");
}
else {
echo(
"<script>alert('username password not matches')</script>");
}
$con->close();
}
?>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css"
href="css/style.css" media="screen" />
<!-- Adding bootstrap -->
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity=
"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity=
"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous">
</script>
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous">
</script>
<div class="nav-bar">
<div class="title">
<h3>welcome to my website</h3>
</div>
</div>
</head>
<body>
<form class="form-login" action="index.php" method="POST">
<div class="form-group">
<label>username</label>
<input type="text" class="form-control"
name="username" id="username"
aria-describedby="emailHelp"
placeholder="username" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control"
name="Password" id="Password"
placeholder="Password" required>
</div>
<button type="submit"
class="btn btn-primary btn-lg">Login
</button>
<button type="button"
class="btn btn-warning btn-lg"
id="register-button">
Create Account
</button>
</form>
<script>
$("#register-button").click(function () {
window.location.replace("register.php");
});
</script>
</body>
</html>

PHP code of profile page: profile.php
PHP
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
?>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css"
href="css/style.css" media="screen" />
<!-- Adding bootstrap -->
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity=
"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity=
"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous">
</script>
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous">
</script>
<div class="nav-bar">
<div class="title">
<h3>welcome to my website</h3>
</div>
</div>
</head>
<body>
<h1>welcome you are loggend in successfully</h1>
</body>
</html>
Output:
Note: In this article the OTP verification process is being done on the client side. This is only for learning purpose, you can do this on the server-side which will be secure.
Similar Reads
PHP Tutorial PHP is a popular, open-source scripting language mainly used in web development. It runs on the server side and generates dynamic content that is displayed on a web application. PHP is easy to embed in HTML, and it allows developers to create interactive web pages and handle tasks like database mana
9 min read
Basics
PHP SyntaxPHP, a powerful server-side scripting language used in web development. Itâs simplicity and ease of use makes it an ideal choice for beginners and experienced developers. This article provides an overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags along with n
4 min read
PHP VariablesA variable in PHP is a container used to store data such as numbers, strings, arrays, or objects. The value stored in a variable can be changed or updated during the execution of the script.All variable names start with a dollar sign ($).Variables can store different data types, like integers, strin
5 min read
PHP | FunctionsA function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
8 min read
PHP LoopsIn PHP, Loops are used to repeat a block of code multiple times based on a given condition. PHP provides several types of loops to handle different scenarios, including while loops, for loops, do...while loops, and foreach loops. In this article, we will discuss the different types of loops in PHP,
4 min read
Array
PHP ArraysArrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
5 min read
PHP Associative ArraysAn associative array in PHP is a special array where each item has a name or label instead of just a number. Usually, arrays use numbers to find things. For example, the first item is at position 0, the second is 1, and so on. But in an associative array, we use words or names to find things. These
4 min read
Multidimensional arrays in PHPMulti-dimensional arrays in PHP are arrays that store other arrays as their elements. Each dimension adds complexity, requiring multiple indices to access elements. Common forms include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing complex, structured data.
5 min read
Sorting Arrays in PHPSorting arrays is one of the most common operation in programming, and PHP provides a several functions to handle array sorting. Sorting arrays in PHP can be done by values or keys, in ascending or descending order. PHP also allows you to create custom sorting functions.Table of ContentSort Array in
4 min read
OOPs & Interfaces
MySQL Database
PHP | MySQL Database IntroductionWhat is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL
4 min read
PHP Database connectionThe collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. Requirements: XAMPP web server procedure: Start XAMPP server by starting Apache and MySQL. Write PHP script f
2 min read
PHP | MySQL ( Creating Database )What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty,
3 min read
PHP | MySQL ( Creating Table )What is a table? In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Creating a
3 min read
PHP Advance
PHP SuperglobalsPHP superglobals are predefined variables that are globally available in all scopes. They are used to handle different types of data, such as input data, server data, session data, and more. These superglobal arrays allow developers to easily work with these global data structures without the need t
6 min read
PHP | Regular ExpressionsRegular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes a
12 min read
PHP Form HandlingForm handling is the process of collecting and processing information that users submit through HTML forms. In PHP, we use special tools called $_POST and $_GET to gather the data from the form. Which tool to use depends on how the form sends the dataâeither through the POST method (more secure, hid
4 min read
PHP File HandlingIn PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a file, creating new files, or deleting existing ones. File handling is essential for applications that require the storage and retrieval of data, such as logging systems, user-generated c
4 min read
PHP | Uploading FileHave you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with - 'Are we able to upload any kind of file with this system?'. The answer is yes, we can upload files with different types
3 min read
PHP CookiesA cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved later, making them ideal for scenarios where you need to remember user preferences, such as:User login status (keeping users logged in between sessions)Language preferences
9 min read
PHP | SessionsA session in PHP is a mechanism that allows data to be stored and accessed across multiple pages on a website. When a user visits a website, PHP creates a unique session ID for that user. This session ID is then stored as a cookie in the user's browser (by default) or passed via the URL. The session
7 min read