Skip to main content

User Account Activation using email Verification using Php

How to Create Basic User Account Activation using email Verification using Php

This tutorial demonstrate to build an email verification script .Email verify is a php script that allows you to verify email address without storing anything in any databases.it will send users an email requiring them to 
click a link to verify their email before  and then your account will be activated...
   And then first, we need to establish a database connection and create a table to insert the account data. So let's go to PHPMyAdmin and create a new database with the name "dbtest" create a user account that has access to that database in order to insert and update data.
download phpmailer form an this link PHPMailer  ..
next,create a table and named as users....

Database: 
create table users(userID int primay key auto_increment not null,userName varchar(30) not null,userEmail varchar(30) not null unique,userPass varchar(30) not null,mdcode varchar(100));
and next ,we have to create empty .php file and named as
1.db.php
2.signup.php
3.user.php
4.verify.php
5.index.php
6.home.php
7.logout.php

1.db.php



<?php
    class db
    {
      private $host='localhost';
      private $uname='root';
      private $password='';
      private $dbname='dbtest';
      public $conn;
      public function dbconnection()
{
    $this->conn=null;
 try
    {

    $this->conn=new PDO('mysql:host='.$this->host.';dbname='.$this->dbname,
    $this->uname,$this->password);
    $this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  }
catch(PDOException $e){echo "connection error".$e->getMessage();}
  return $this->conn;
   } 
 }
?>

2.signup.php



<?php

session_start();

require_once 'user.php';

$user=new USER();

if($user->is_logged_in()!="")

{

 $user->redirect('home.php');

}

if(isset($_POST['submit']))

{

 $uname=trim($_POST['username']);

 $email=trim($_POST['email']);

 $pass=trim($_POST['password']);

 $code=md5(uniqid(rand()));

 $stmt=$user->query("select * from users where userEmail=:emailid");

 $stmt->execute(array("emailid"=>$email));

 $row=$stmt->fetch(PDO::FETCH_ASSOC);

 if($stmt->rowCount() > 0)

 {

  $msg="<strong>sorry! </strong> email is already taken try another..";

 }

 else

 {

  if($user->register($uname,$email,$pass,$code))

  {

   $id=$user->lastid();

   $key=base64_encode($id);

   $id=$key;

   $message="

      hello $email.<br/><br/>

      welcome to blogger<br/>

 <a href='http://localhost/testsignup1/verify.php?userID=$id&mdcode=$code'>click here to acitvate</a>";

      $subject="confirm registration";

      $user->sendmail($email,$message,$subject);

        $msg = "

                            <strong>Success!</strong>  We've sent an email to $email.

                    Please click on the confirmation link in the email to create your account. 

    ";

    

  }

  else

  {

   echo "sorry...error may occured";

  }

 }

}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Untitled Document</title>

</head>



<body>

<?php if(isset($msg)) echo $msg; ?>

<form method="post">

   <input type="text" name="username" placeholder="username" /><br />

   <input type="email" name="email" placeholder="Email" /><br />

   <input type="password" name="password" placeholder="password" /><br />

   <input type="submit" name="submit" value="submit" /><br />

</form>
</body>

</html>


 $id=$user->lastid()-this condition check the lastid in user.php and there is an condition lastInsertId() get the userid  assign to $id
so we create a variable named as $key and assinged ($id)  is encode with base64 it was unique to find and covert very easy in email verify ..so base 64 the value is like MTU or uTT 
and then $key is assigned to $id....its $id and then $code is sended to sendmail() function to mail id and when you click to verify by mail the account will be activated....

3.users.php


<?php

require_once 'db.php';

class USER

{

 private $conn;

        public function __construct()

 {

  $database=new db();

  $db=$database->dbconnection();

  $this->conn=$db;

 } 

 public function query($sql)

 {

  $stmt=$this->conn->prepare($sql);

  return $stmt;

 }

 public function lastid(){

     $stmt=$this->conn->lastInsertId();

  return $stmt; 

  }

 

 public function login($email,$password)

 {

   try

  {

 $stmt = $this->conn->prepare("SELECT * FROM users WHERE userEmail=:email_id");

   $stmt->execute(array(":email_id"=>$email));

   $userRow=$stmt->fetch(PDO::FETCH_ASSOC);

   

   if($stmt->rowCount() == 1)

   {

    if($userRow['userStatus']=="Y")

    {

     if($userRow['userPass']==md5($password))

     {

      $_SESSION['userSession'] = $userRow['userID'];

      return true;

     }

     else

     {

      header("Location: index.php?error");

      exit;

     }

    }

    else

    {

     header("Location: index.php?inactive");

     exit;

    } 

   }

   else

   {

    header("Location: index.php?error");

    exit;

   }  

  }

  catch(PDOException $ex)

  {

   echo $ex->getMessage();

  }

 }

 

  public function redirect($url)

 {

  header("location:$url");

 }

  public function is_logged_in()

      {

        if(isset($_SESSION['userSession']))

        {

        return true;

       }

      }

  public function register($uname,$email,$pass,$code)

 {

  try{

  $password=md5($pass);

  $stmt=$this->conn->prepare("insert into users (userName,userEmail,userPass,mdcode) values(:uname,:email,:pass,:code)");

  $stmt->bindparam(':uname',$uname);

  $stmt->bindparam(':email',$email);

  $stmt->bindparam(':pass',$password);

  $stmt->bindparam(':code',$code);

  $stmt->execute();

  return $stmt;

  }

catch(PDOException $e){echo "error:".$e->getMessage();}

  }

 public function logout()

 {

  session_destroy();

  $_SESSION['username'] = false;

 }

 

 function sendmail($email,$message,$subject)

 {      

  require_once('mailer/class.phpmailer.php');

  require_once('mailer/class.smtp.php');

  $mail = new PHPMailer;

  $mail->IsSMTP(); 

  $mail->SMTPDebug  = 2;                     

  $mail->SMTPAuth   = true;                  

  $mail->SMTPSecure = "tls";                 

  $mail->Host       = "smtp.gmail.com";      

  $mail->Port       = 587;       

  $mail->isHTML(true);        

  $mail->AddAddress($email);

  $mail->Username="chandra2555@gmail.com";  

  $mail->Password="chandra2555";            

  $mail->SetFrom('chandra2555@gmail.com','chandra Blogspot');

  $mail->Subject    = $subject;

  $mail->MsgHTML($message);

  if(!$mail->Send())

  {

   echo "message is not sent";

}

else{echo "message is sent to your email id";}



 } 

}

?>


     sendmail()-send mail is so complicated think ....lot of people having SMTP() failed and show blank and ssl is not working and tls is not working and port assigned is showing an error lot of problem facing but you are using a membership website it will works very easy but you have to free webhost it not work because hosting is not provide the permission to uses your gmail mail id ....what to do ....follow my instruction ...
once again......am using xampp for local sever and download phpmailer from above link i mention on top ...and then get sample code form same website ...
and then error SMTP() can occur only adding class.phpmailer.php  so add another file class.smtp.php in phpmailer it can solve the error and you got msg mail send successfully and then all before you have to do some changes  on your emailid see on below image 
    login gmail ->myaccount->connected apps and sites ->less secure app->on that's it .....
User Account Activation using email Verification using Php
User Account Activation using email Verification using Php

4.Verify.php


<?php

require_once 'user.php';

$user = new USER();



if(empty($_GET['userID']) && empty($_GET['mdcode']))

{

 $user->redirect('index.php');

}



if(isset($_GET['userID']) && isset($_GET['mdcode']))

{

 $id = base64_decode($_GET['userID']);

 $code = $_GET['mdcode'];

 $statusY = "Y";

 $statusN = "N";

 $stmt = $user->query("SELECT userID,userStatus FROM users WHERE userID=:uID AND mdcode=:code LIMIT 1");

 $stmt->execute(array(":uID"=>$id,":code"=>$code));

 $row=$stmt->fetch(PDO::FETCH_ASSOC);

 if($stmt->rowCount() > 0)

 {

  if($row['userStatus']==$statusN)

  {

   $stmt = $user->query("UPDATE users1 SET userStatus=:status WHERE userID=:uID");

   $stmt->bindparam(":status",$statusY);

   $stmt->bindparam(":uID",$id);

   $stmt->execute(); 

   

   $msg = "

             

       <strong>Awesome !</strong>  Your Account is Now Activated : 

<a href='index.php'>Login here</a>

         

          "; 

  }

  else

  {

   $msg = "

             

       <strong>sorry !</strong>  Your Account is already Activated : 

<a href='index.php'>Login here</a>

        

          ";

  }

 }

 else

 {

  $msg = "

         

      <strong>sorry !</strong>  No Account Found : <a href='signup.php'>Signup here</a>

   

      ";

 } 

}



?>

<!DOCTYPE html>

<html>

  <head>

    <title>Confirm Registration</title>

    

  </head>

  <body id="login">

    <div class="container">

  <?php if(isset($msg)) { echo $msg; } ?>

    </div>
</body>

</html>

5.index.php



<?php

session_start();

require 'user.php';

$login=new USER();

if($login->is_logged_in()!="")

{

 $login->redirect('home.php');

}

if(isset($_POST['submit']))

{

 $email=trim($_POST['email']);

 $password=trim($_POST['password']);

    if($login->login($email,$password))

 {

  $login->redirect('home.php');

 }



}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Untitled Document</title>

</head>



<body>

<?php

 if(isset($_GET['inactive']))

  {

   ?>

            

    <strong>Sorry!</strong> This Account is not Activated Go to your Inbox and Activate it. 

            <?php

  }

  ?>



<form method="post">

    <?php

        if(isset($_GET['error']))

  {

   ?>

            

    <strong>Wrong Details!</strong> 

   </div>
<?php

  }

  ?>

 <input type="text" name="email"  placeholder="email" />

  <input type="password" name="password" placeholder="password" />

  <input type="submit" name="submit" value="submit"/>

  <a href="signup.php" >signup</a>

</form>
</body>

</html>



6.Home.php


<?php

session_start();

require_once 'user.php';

$user=new USER();

if(!$user->is_logged_in()){

    $user->redirect('index.php'); 

 }





$stmt=$user->query("select * from users where userID=:emailid");

$stmt->execute(array(":emailid"=>$_SESSION['userSession']));

$row=$stmt->fetch(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Untitled Document</title>

</head>



<body>

hi      <?php echo $_SESSION['userSession'];?>      <?php  echo $row['userEmail'];?>   <a href="logout.php">logout</a>

</body>

</html>


7.logout.php


<?php

session_start();

require_once 'user.php';

$user = new USER();



if(!$user->is_logged_in())

{

 $user->redirect('index.php');

}



if($user->is_logged_in()!="")

{

 $user->logout(); 

 $user->redirect('index.php');

}

?>



In this step we get the User Account Activation using email Verification using Php. That's all, this is how to User Account Activation using email Verification using Php. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Comments

Popular posts from this blog

Contact Management System project using C with source code

Contact Management System (CMS)   A Contact Management System (CMS) is an essential application for organizing and managing contacts efficiently. Here's a simple implementation of a Contact Management System using C, allows users to perform operations such as adding, viewing, searching, modifying, and deleting contacts through a simple and user-friendly console interface. The CMS provides a practical demonstration of fundamental programming concepts such as arrays, structures, and string manipulation, making it an excellent project for students and beginners in C programming.   Project Overview The Contact Management System is designed to store basic information about contacts, including: Name: name of the person. Phone Number: phone number of the contact. Email Address: email address of the contact.   With this information, the program offers the following functionalities: Add New Contact...

Implementing Basic Add to Cart Functionality in Python Using Flask

In e-commerce websites, the "Add to Cart" feature allows users to select products they want to purchase and store them temporarily while they continue shopping. Implementing this functionality in a web application using Python and Flask is straightforward and can be done with a few simple steps.       Setting Up the Project: First, create a new directory for your project and set up a virtual environment to manage dependencies. Install Flask using pip and create three main files: `app.py`, `index.html`, and `cart.html`.   Read also:   Unlocking the Power of Free Google Tools for Seo Success Ultimate Guide: Google Search Console Crawl Reports you need to know Monitor What is dofollow backlinks: The ultimate 5 Benefit for your websites SEO Schema markup and How can you use schema markup for seo      Creating HTML Templates: Create HTML templates for displaying products (`index.html`) and the shopping cart (`cart.html`). These templates will use ...

Advanced HTML Concepts: Techniques and Examples for Modern Web Development

Advanced HTML goes beyond the basics of creating simple web pages, delving into powerful features and techniques that improve web interactivity, accessibility, and performance. It includes concepts such as semantic HTML, custom data attributes, responsive images with <picture> , enhanced forms, interactive content using <details> and <summary> , and embedding external resources with <iframe> .          Furthermore, advanced HTML focuses on SEO optimization through meta tags, accessibility improvements using ARIA, creating reusable Web Components, and optimizing performance with async and defer scripts.    Semantic HTML   Semantic elements clearly describe their meaning in a human- and machine-readable way.   <header> <h1>Welcome to My Website</h1> </header> <nav> <ul> <li><a href="home">Home...

Python Flask Student List CRUD System Using MySQL Database for Beginners

  In this tutorial, we are going to learn the python flask student list crud system using MySQL database for beginners. Before you have to learn how to python flask setting up and connect MySQL database connection and templates uses.    Read also: Python Flask tutorial Setting up a Flask and Sql Database on the create project folder you have to install two things to fetch data and flask. Here, below code to install using python terminal, and for MySQL, am using xampp software and database inside environment to turn on the apache server and MySQL database.   Read also: Python Flask with Mysql Database Import Flask and MySQL: from flask import Flask, render_template, request, redirect, url_for from flask_mysqldb import MySQL MySQL Database Connection: app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] ...

Microdata Schema : How can Microdata schema Improve SEO with Examples

In this article, we will explore what microdata schema is, how it works, and provide some examples to help you better understand its importance. What is Microdata Schema? Microdata schema is a markup language that provides a standardized way of adding structured data to web pages. It uses HTML tags to describe information about the content on a web page, such as product reviews, events, recipes, and more. This makes it easier for search engines to crawl and index the content on a web page, which can help improve the visibility and ranking of the website. How Does Microdata Schema Work? Microdata schema uses a set of properties and item types to describe the content on a web page. Properties describe specific attributes of an item, while item types describe the type of item being described. For example, the property "name" might be used to describe the name of a person, while the item type "Person" would be used to indicate that the content being describ...

How to Create a Personal details information program in HTML

In this tutorial, we are learning how you can create a personal details information program in HTML with the simple using of HTML tags. HTML Form: <div class="container"> <h1 style="text-align:center">Personal Details</h1> <form class="form-control"> <label for="name">Name:</label><br> <input type="text" id="name" name="name"><br> <label for="email">Email:</label><br> <input type="email" id="email" name="email"><br> <label for="dob">Date of Birth:</label><br> <input type="date" id="dob" name="dob"><br> <label for="gender">Gender:</label><br> <input type="radio" id="gender" name="gender" value="male...