Monday, 4 December 2017

PHP Registration Script with Email Confirmation

In this post, We have start learning how can we send user activation email after completing user registration. Because if you have created an account on any website and have you verify you email by click through a verification link send by website for activate or verify email which you have enter email at the time of registration. So we have make this post to learn how can you build an email verification script step by step.

This is email verify PHP script in which you allows you to verify your email address at the time of registration. This email verification script used at the time of new registration or this script also required when in your site has rss subscription, then use has enter email for subscribe rss feed. So email must be original and reduce spam. So At that time we want to verify email address by sending verification link to that email address.

Here we have use simple PHP registration example to verify email address by sending email activation link to their account and by clicking on that link email will be verified. For make this script we have use PHP PDO script with Mysql Database and for sending email we have use PHPMailer Library. In this script user can register into site by entering proper email and after register with email address, then they will received email verification link into their email address. So if email will be proper then he will received email verification link. If user not verified their email address then he cannot login into site. For access website user want to verify their email address. This script helpful to reduce spam registration into website. For email verification user has go to email account and in his email address he will received email verification link with password. So user can verify email by clicking on that link. After email verification user can also received password in his email also. After this email verification user can login into system. This way we can verify email address for reduce span registration by using PHP PDO with Mysql Database and PHPMailer Library.








Source Code


database_connection.php



<?php
//database_connection.php

$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
session_start();

?>


register.php



<?php
//register.php

include('database_connection.php');

if(isset($_SESSION['user_id']))
{
 header("location:index.php");
}

$message = '';

if(isset($_POST["register"]))
{
 $query = "
 SELECT * FROM register_user 
 WHERE user_email = :user_email
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':user_email' => $_POST['user_email']
  )
 );
 $no_of_row = $statement->rowCount();
 if($no_of_row > 0)
 {
  $message = '<label class="text-danger">Email Already Exits</label>';
 }
 else
 {
  $user_password = rand(100000,999999);
  $user_encrypted_password = password_hash($user_password, PASSWORD_DEFAULT);
  $user_activation_code = md5(rand());
  $insert_query = "
  INSERT INTO register_user 
  (user_name, user_email, user_password, user_activation_code, user_email_status) 
  VALUES (:user_name, :user_email, :user_password, :user_activation_code, :user_email_status)
  ";
  $statement = $connect->prepare($insert_query);
  $statement->execute(
   array(
    ':user_name'   => $_POST['user_name'],
    ':user_email'   => $_POST['user_email'],
    ':user_password'  => $user_encrypted_password,
    ':user_activation_code' => $user_activation_code,
    ':user_email_status' => 'not verified'
   )
  );
  $result = $statement->fetchAll();
  if(isset($result))
  {
   $base_url = "http://localhost/tutorial/email-address-verification-script-using-php/";
   $mail_body = "
   <p>Hi ".$_POST['user_name'].",</p>
   <p>Thanks for Registration. Your password is ".$user_password.", This password will work only after your email verification.</p>
   <p>Please Open this link to verified your email address - ".$base_url."email_verification.php?activation_code=".$user_activation_code."
   <p>Best Regards,<br />Webslesson</p>
   ";
   require 'class/class.phpmailer.php';
   $mail = new PHPMailer;
   $mail->IsSMTP();        //Sets Mailer to send message using SMTP
   $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts of your Email hosting, this for Godaddy
   $mail->Port = '80';        //Sets the default SMTP server port
   $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
   $mail->Username = 'xxxxxxxx';     //Sets SMTP username
   $mail->Password = 'xxxxxxxx';     //Sets SMTP password
   $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
   $mail->From = 'info@webslesson.info';   //Sets the From email address for the message
   $mail->FromName = 'Webslesson';     //Sets the From name of the message
   $mail->AddAddress($_POST['user_email'], $_POST['user_name']);  //Adds a "To" address   
   $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
   $mail->IsHTML(true);       //Sets message type to HTML    
   $mail->Subject = 'Email Verification';   //Sets the Subject of the message
   $mail->Body = $mail_body;       //An HTML or plain text message body
   if($mail->Send())        //Send an Email. Return true on success or false on error
   {
    $message = '<label class="text-success">Register Done, Please check your mail.</label>';
   }
  }
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Register Login Script with Email Verification</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container" style="width:100%; max-width:600px">
   <h2 align="center">PHP Register Login Script with Email Verification</h2>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading"><h4>Register</h4></div>
    <div class="panel-body">
     <form method="post" id="register_form">
      <?php echo $message; ?>
      <div class="form-group">
       <label>User Name</label>
       <input type="text" name="user_name" class="form-control" pattern="[a-zA-Z ]+" required />
      </div>
      <div class="form-group">
       <label>User Email</label>
       <input type="email" name="user_email" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="register" id="register" value="Register" class="btn btn-info" />
      </div>
     </form>
     <p align="right"><a href="login.php">Login</a></p>
    </div>
   </div>
  </div>
 </body>
</html>


email_verification.php



<?php

include('database_connection.php');

$message = '';

if(isset($_GET['activation_code']))
{
 $query = "
  SELECT * FROM register_user 
  WHERE user_activation_code = :user_activation_code
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':user_activation_code'   => $_GET['activation_code']
  )
 );
 $no_of_row = $statement->rowCount();
 
 if($no_of_row > 0)
 {
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   if($row['user_email_status'] == 'not verified')
   {
    $update_query = "
    UPDATE register_user 
    SET user_email_status = 'verified' 
    WHERE register_user_id = '".$row['register_user_id']."'
    ";
    $statement = $connect->prepare($update_query);
    $statement->execute();
    $sub_result = $statement->fetchAll();
    if(isset($sub_result))
    {
     $message = '<label class="text-success">Your Email Address Successfully Verified <br />You can login here - <a href="login.php">Login</a></label>';
    }
   }
   else
   {
    $message = '<label class="text-info">Your Email Address Already Verified</label>';
   }
  }
 }
 else
 {
  $message = '<label class="text-danger">Invalid Link</label>';
 }
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Register Login Script with Email Verification</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  
  <div class="container">
   <h1 align="center">PHP Register Login Script with Email Verification</h1>
  
   <h3><?php echo $message; ?></h3>
   
  </div>
 
 </body>
 
</html>


login.php



<?php
//login.php

include('database_connection.php');

if(isset($_SESSION['user_id']))
{
 header("location:index.php");
}

$message = '';

if(isset($_POST["login"]))
{
 $query = "
 SELECT * FROM register_user 
  WHERE user_email = :user_email
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
    'user_email' => $_POST["user_email"]
  )
 );
 $count = $statement->rowCount();
 if($count > 0)
 {
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   if($row['user_email_status'] == 'verified')
   {
    if(password_verify($_POST["user_password"], $row["user_password"]))
    {
     $_SESSION['user_id'] = $row['register_user_id'];
     header("location:index.php");
    }
    else
    {
     $message = "<label>Wrong Password</label>";
    }
   }
   else
   {
    $message = "<label class='text-danger'>Please First Verify, your email address</label>";
   }
  }
 }
 else
 {
  $message = "<label class='text-danger'>Wrong Email Address</label>";
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Register Login Script with Email Verification</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container" style="width:100%; max-width:600px">
   <h2 align="center">PHP Register Login Script with Email Verification</h2>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading"><h4>Login</h4></div>
    <div class="panel-body">
     <form method="post">
      <?php echo $message; ?>
      <div class="form-group">
       <label>User Email</label>
       <input type="email" name="user_email" class="form-control" required />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="user_password" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="login" value="Login" class="btn btn-info" />
      </div>
     </form>
     <p align="right"><a href="register.php">Register</a></p>
    </div>
   </div>
  </div>
 </body>
</html>


logout.php



<?php
//logout.php
session_start();

session_destroy();

header("location:login.php");

?>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `register_user`
--

CREATE TABLE IF NOT EXISTS `register_user` (
  `register_user_id` int(11) NOT NULL,
  `user_name` varchar(250) NOT NULL,
  `user_email` varchar(250) NOT NULL,
  `user_password` varchar(250) NOT NULL,
  `user_activation_code` varchar(250) NOT NULL,
  `user_email_status` enum('not verified','verified') NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `register_user`
--

INSERT INTO `register_user` (`register_user_id`, `user_name`, `user_email`, `user_password`, `user_activation_code`, `user_email_status`) VALUES
(1, 'John Smith', 'web-tutorial@programmer.net', '$2y$10$vdMwAmoRJfep8Vl4BI0QDOXArOCTOMbFs6Ja15qq3NEkPUBBtffD2', 'c74c4bf0dad9cbae3d80faa054b7d8ca', 'verified');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `register_user`
--
ALTER TABLE `register_user`
  ADD PRIMARY KEY (`register_user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `register_user`
--
ALTER TABLE `register_user`
  MODIFY `register_user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

26 comments:

  1. Hi, i got the following error - Fatal error: Call to undefined function password_hash() in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\Test10\register.php on line 33

    ReplyDelete
  2. Hi, thank you for sharing, is it compulsory to set SMTP username and password?

    ReplyDelete
  3. nice code please visit my blog www.gajabwap.blogspot.in

    ReplyDelete
  4. hello sir.
    Do you make google map calculate distance between two places with detraction.

    ReplyDelete
  5. how to stop flash message showing in the script

    ReplyDelete
  6. I got a question.
    how to set SMTP in localhost?
    because when I try this method, it could'n send any code to my email.
    please help me:(

    ReplyDelete
    Replies
    1. you can not set SMTP in localhost...to activate SMTP you need to push your project on server ..@sasi Thiago

      Delete
    2. This may help you to send email from Localhost.
      https://stackoverflow.com/questions/15965376/how-to-configure-xampp-to-send-mail-from-localhost

      Delete
    3. you should download composer from GitHub https://getcomposer.org/ and then open your command prompt and choose your drive and Xampp folder in which you want to upload the phpmaler class and then run the "composer require phpmailer/phpmailer" command on your command prompt and then include the 'vendor/autoload.php' in your php mail code then it will work.

      Delete
    4. i already follow youe step cant's work also

      Delete
  7. i have the same problem
    ii couldnt send me an email
    please help!

    ReplyDelete
  8. i have the same problem
    ii couldnt send me an email
    please help!

    ReplyDelete
  9. nice article. but how PHP Registration Script with Phone Number Confirmation. Please Help Me.

    ReplyDelete
    Replies
    1. I have the same inquiry can you help me?

      Delete
  10. Hi. Nice Tutorial. I cant send email. I think phpMailer not send email but i can add data in database. Maybe the problem is the phpMailer.

    ReplyDelete
  11. Can you create forgot password system using this registration system? thanks sir..

    ReplyDelete
  12. hello i have a problem with setting up a variable for user_name can u help me?

    ReplyDelete
  13. cant send email - help please

    ReplyDelete
  14. Hi, works great except after I verify the email, I cannot use the password I registered with to login. Only was it works is I have to reset the password, any ideas?

    ReplyDelete
  15. Hi, works great except having a weird issue. So the password I chose to register an account with doesn't work after I have been verified. Only was it works is to reset the password. Any ideas?

    ReplyDelete
  16. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
    if its still not working for you

    ReplyDelete
  17. Question. My email is not sending thougt I have smtp set up corectly )godaddy, port 80, smtpout.secureserver.net) errorlog indicates the problem happens at line 50 in register.php.
    That line is: $result = $statement->fetchAll();

    Any thoughts?

    ReplyDelete
  18. Thanks for sharing. By the way that is not include password reset form?

    ReplyDelete
  19. Hello! I have this error does someone know what its about?

    Fatal error: Uncaught Error: Class 'PHPMailer' not found in /opt/lampp/htdocs/Email/register.php:61 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/Email/register.php on line 61

    ReplyDelete