How to Create Registration with Email Verification in PHP MySQL

1 53,338

Hi Freinds in this article we will discuss about How to create Registration  with Email Verification in PHP MySQL. in this post you will learn all you need to create a registration system with email verification system in PHP. This post take you throgh the whole process in a step step manner so that you can learn progressively and enhance your skills. I will be explain all the step in easy to understand manner.

How to Create Registration with Email Verification in PHP MySQL

1-Creating Database

  • Open Phpmyadmin in your Browser
  • Click on Database Tab Display on Top side
  • Give the Database name “registration”.
  • After Creating Database Open it.
  • Click on SQL Tab on Top area
  • Copy the Below Source Code and paste it.
  • Then Click on Go.
-- phpMyAdmin SQL Dump
-- version 4.2.7.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: May 10, 2016 at 04:45 PM
-- Server version: 5.6.20
-- PHP Version: 5.5.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `registration`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `token` varchar(255) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=24 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email`, `password`, `token`, `status`) VALUES
(23, 'Deepak', 'deepak.suhawal@gmail.com', '00124578', '092c1caafc3ff7d1de61a110a5b46462f1d01644f212fc214a18d2528067308b', 1);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
 ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=24;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

OR Import DB File

After Downloading the source code extract it in your root folder.

  • Open Phpmyadmin in your Browser
  • Click on Database Tab Display on Top side
  • Give the Database name “registration”.
  • After Creating Database Open it.
  • Click on Import Tab on Top area
  • You can Find Db file in  Downloaded source code Select it.
  • Then Click on Go.

2- Creating Database Connection

After import Database File then next step is creating database connection using php copy the below code and save it is as “db.php”.

<?php

$db = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);

?>

and create another file named “config.php” and put the below source code to complete database connection.

<?php

define("DB_HOST" ,"localhost");
define("DB_USER" ,"root");
define("DB_PASS" ,"");
define("DB_NAME" ,"registration");

?>

 

3 – Creating Login and Registration Form

In this step  we are going to create login  form in HTML.

 <form action="index.php" method="post" style="margin-top:35px;">
         <h2>Login</h2>
         
         <?php if(isset($_GET['success'])) { ?>
         
         <div class="alert alert-success"><?php echo $_GET['success']; ?></div>
         
         <?php } ?>
         
         <?php if(isset($_GET['err'])) { ?>
         
         <div class="alert alert-danger"><?php echo $_GET['err']; ?></div>
         
         <?php } ?>
         
         <hr>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" name="email" class="form-control" placeholder="Email">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" name="password" class="form-control" placeholder="Password">
  </div>
 
  <div class="checkbox">
    <label>
      <input type="checkbox" name="remember_me"> Remember Me
    </label>
  </div>
  <button type="submit" name="login" class="btn btn-default">Login</button>
  <a href="#">Forgot Password?</a>
</form>

In this step  we are going to create Registration form in HTML.

 <form  action="register.php" method="post" style="margin-top:35px;">
         <h2>Register Here</h2>
         
         <?php if(isset($_GET['err'])) { ?>
         
         <div class="alert alert-danger"><?php echo $_GET['err']; ?></div>
         
         <?php } ?>
         <hr>
         <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" placeholder="Name" value="<?php echo @$_SESSION['name']; ?>" required>
  </div>
     
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" name="email" class="form-control" placeholder="Email" value="<?php echo @$_SESSION['email']; ?>" required>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" name="password" class="form-control" placeholder="Password" value="<?php echo @$_SESSION['password']; ?>" required>
  </div>
 
 <div class="form-group">
    <label >Confirm Password</label>
    <input type="password" name="confirm_password" class="form-control" placeholder="Confirm Password" value="<?php echo @$_SESSION['confirm_password']; ?>" required>
  </div>
 
  <button type="submit" name="register" class="btn btn-default">Register</button>
</form>

4 – Insert Data into Database and Send Verification using PHP

in this we are going to insert data into database through registration form and send verification mail using php.

<?php
session_start();

include('includes/config.php');
include('includes/db.php');
include('includes/functions.php');


if(loggedIn()){
    header("Location:myaccount.php");
    exit();
}

function isUnique($email){
    $query = "select * from users where email='$email'";
    global $db;
    
    $result = $db->query($query);
    
    if($result->num_rows > 0){
        return false;
    }
    else return true;
    
}

if(isset($_POST['register'])){
    $_SESSION['name'] = $_POST['name'];
    $_SESSION['email'] = $_POST['email'];
    $_SESSION['password'] = $_POST['password'];
    $_SESSION['confirm_password'] = $_POST['confirm_password'];
    
    if(strlen($_POST['name'])<3){
        header("Location:register.php?err=" . urlencode("The name must be at least 3 characters long"));
        exit();
    }
   else if($_POST['password'] != $_POST['confirm_password']){
        header("Location:register.php?err=" . urlencode("The password and confirm password do not match"));
        exit();
   }
    else if(strlen($_POST['password']) < 5){
         header("Location:register.php?err=" . urlencode("The password should be at least 5 characters"));
        exit();
    }
  
    else if(!isUnique($_POST['email'])){
        header("Location:register.php?err=" . urlencode("Email is already in use. Please use another one"));
        exit();
    }
   
    else {
        $name = mysqli_real_escape_string($db , $_POST['name']);
        $email = mysqli_real_escape_string($db , $_POST['email']);
        $password = mysqli_real_escape_string($db , $_POST['password']);
        $token = bin2hex(openssl_random_pseudo_bytes(32));
        
        $query = "insert into users (name,email,password,token) values('$name','$email','$password','$token')";
        
        $db->query($query);
        $message = "Hi $name! Account created here is the activation link http://localhost/registration/activate.php?token=$token";
        
        mail($email , 'Activate Account' , $message , 'From: deepak.suhawal@gmail.com');
        header("Location:index.php?success=" . urlencode("Activation Email Sent!"));
        exit();
    }
   
}
?>

5 – Email Activation using PHP

after sending verification we need to activate and this step we will learn how to activate registration using PHP.

<?php

include('includes/config.php');
include('includes/db.php');

if(isset($_GET['token'])){
    $token = $_GET['token'];
    $query = "update users set status='1' where token='$token'";
    if($db->query($query)){
        header("Location:index.php?success=Account Activated!!");
        exit();
    }
    
}

?>

6 – Validating Login Form using PHP

in this step we are going to validate login form to access login panel.

<?php
session_start();

include('includes/config.php');
include('includes/db.php');
include('includes/functions.php');

if(loggedIn()){
    header("Location:myaccount.php");
    exit();
}

if(isset($_POST['login'])){
    $email = mysqli_real_escape_string($db , $_POST['email']);
    $password = mysqli_real_escape_string($db , $_POST['password']);
    
    $query = "select * from users where email='$email' and password='$password'";
    
    $result = $db->query($query);
    
    if($row = $result->fetch_assoc()){
        if($row['status'] == 1){
            $_SESSION['user_email'] = $email;
            if(isset($_POST['remember_me'])){
                setcookie("user_email" , $email , time()+60*5);
            }
            header("Location:myaccount.php");
            exit();
        }else {
            header("Location:index.php?err=" . urlencode("The user account is not activated!"));
            exit();
        }
    }else {
        header("Location:index.php?err=" . urlencode("Wrong Email or Password!"));
            exit();
    }
}

?>

7 – Creating Myaccount page For login users only

In this step creating a page named “myaccount.php” if a user login then this page will appear.

<?php
session_start();
include('includes/config.php');
include('includes/db.php');
include('includes/functions.php');

if(!loggedIn()){
    header("Location:index.php?err=" . urlencode("You need to login to View account!!"));
    exit();
}

?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Account</title>
    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

  </head>

  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="http://sourcecodessite.com">Download SOurce Code Free</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li><a href="index.php">Login</a></li>
            <li><a href="register.php">Register</a></li>
            <li><a href="logout.php">Logout</a></li>

          </ul>
        </div>
      </div>
    </nav>

    <div class="container">
<br>

    	<div class="jumbotron">
			<h2>Welcome <?php  if(isset($_SESSION['user_email'])) {echo $_SESSION['user_email'];} else echo $_COOKIE['user_email']; ?></h2>
		</div>

    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="js/bootstrap.js"></script>
    
  </body>
</html>

8 – Set Seesion and Cookies

in this step we need to create function page and where set session and cookies.

<?php


function loggedIn(){
    if(isset($_SESSION['user_email']) || isset($_COOKIE['user_email'])){
        return true;
    }else return false;
}

?>

9 – Creating Logout Function using PHP

after login we need to logout and in this step we are creating a logout function using PHP .

<?php

session_start();

session_destroy();

setcookie("user_email" , "" , time()-60*5);
header("Location:index.php?success=" . urlencode("Logged Out Successfully!"));
exit();

?>

If you facing any type of problem with this source code then you can Download the Complete source code in zip Formate by clicking the below button Download Now otherwise you can send Comment.

Download Updated Code

1 Comment
  1. chandan says

    my php gmail connection some error .can you help me . my whats app number is 8271579452.

Leave A Reply

Your email address will not be published.