Post image for Building A registration System with Email verification in PHP

Building A registration System with Email verification in PHP

by Hyder on April 1, 2010

in PHP

Have you ever registered on a website and you were required to activate your newly created account via a confirmation link sent to the email address you supplied while registering? This Email verification “Mechanism” is very common nowadays especially in forums, popular websites such as ebay, paypal, Facebook etc .Verifying Email Address helps to reduce spam and also to make sure that the email supplied belongs to that member.

What are we going to build ?

We are going to build a small system in which a user can register a new account. After registration, a confirmation link will be emailed to the email supplied in the registration form. The user will have to log in his email Account and click the activation link. After that, He or she or she  will be able to login into the system. Before Going into the code, here is some screenshot of how it is going to work.

After Successful registration, an Activation will be emailed to the user in order to verify that the email address supplied  is really his.

On Clicking the Activation link , A message will be displayed whether Account has been Activated successfully or not.

The user may now login .

If Login is successful,  He or she will be redirected to page.php, which could be called the “member Area”

Step 1: Database Connection File



This file contains the Database Connection Information.  It Also contains the Sender’s email address,website url and the smtp server address. Please change these settings accordingly. IF you are going to host this
script on  a server at  hostgator , namecheap , godaddy etc , there’s a great chance you would not need the “SMTP” part .Simply Remove this line of code.

<?php

/*Define constant to connect to database */
DEFINE('DATABASE_USER', 'root');
DEFINE('DATABASE_PASSWORD', '');
DEFINE('DATABASE_HOST', 'localhost');
DEFINE('DATABASE_NAME', 'forum');
/*Default time zone ,to be able to send mail */
date_default_timezone_set('UTC');

/*You might not need this */
ini_set('SMTP', "mail.myt.mu");
// Overide The Default Php.ini settings for sending mail

//This is the address that will appear coming from ( Sender )
define('EMAIL', 'email@gmail.com');

/*Define the root url where the script will be found such as
http://website.com or http://website.com/Folder/ */
DEFINE('WEBSITE_URL', 'http://localhost');

// Make the connection:
$dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
 DATABASE_NAME);

if (!$dbc) {
 trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}

?>

Database Structure


--
-- Table structure for table `members`
--

CREATE TABLE IF NOT EXISTS `members` (
 `Memberid` int(10) NOT NULL AUTO_INCREMENT,
 `Username` varchar(20) NOT NULL,
 `Email` varchar(20) NOT NULL,
 `Password` varchar(10) NOT NULL,
 `Activation` varchar(40) DEFAULT NULL,
 PRIMARY KEY (`Memberid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=22 ;

Step 2 : Registration Page

The CSS Part has been omitted here . You can read a detailed description of how this form has been built using pure css .

<form action="index.php" method="post" class="registration_form">
  <fieldset>
    <legend>Registration Form </legend>

    <p>Create A new Account <span style="background:#EAEAEA none repeat scroll 0 0;line-height:1;margin-left:210px;;padding:5px 7px;">
Already a member? <a href="login.php">Log in</a></span> </p>

    <div class="elements">
      <label for="name">Name :</label>
      <input type="text" id="name" name="name" size="25" />
    </div>
    <div class="elements">
      <label for="e-mail">E-mail :</label>
      <input type="text" id="e-mail" name="e-mail" size="25" />
    </div>
    <div class="elements">
      <label for="Password">Password:</label>
      <input type="password" id="Password" name="Password" size="25" />
    </div>
    <div class="submit">
     <input type="hidden" name="formsubmitted" value="TRUE" />
      <input type="submit" value="Register" />
    </div>
  </fieldset>
</form>

Code to Handle the Registration Form Submission :

Basic Form Validation Rules :

  • Make sure no field is empty .
  • Validate Email Address Format .

If  Form Validation is successfull a unique activation code is created using the php built in function MD5 () .For each new account , a unique activation key is sent along the email address of the member.The md5 key is then added to the database field “Activation” .

The Activation Link is in this format  :

http://website.com/activate.php?email=admin@example.com&key=c47662ba2504508bcdd5cb75106110a6

include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
    $error = array(); //Declare An Array to store any error message
    if (empty($_POST['name'])) { //if no name has been supplied
        $error[] = 'Please Enter a name '; //add to array "error"
    } else {
        $name = $_POST['name']; //else assign it a variable
    }

    if (empty($_POST['e-mail'])) {
        $error[] = 'Please Enter your Email ';
    } else {

        if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",
            $_POST['e-mail'])) {
            //regular expression for email validation
            $Email = $_POST['e-mail'];
        } else {
            $error[] = 'Your EMail Address is invalid  ';
        }

    }

    if (empty($_POST['Password'])) {
        $error[] = 'Please Enter Your Password ';
    } else {
        $Password = $_POST['Password'];
    }

    if (empty($error)) //send to Database if there's no error '

    { // If everything's OK...

        // Make sure the email address is available:
        $query_verify_email = "SELECT * FROM members  WHERE Email ='$Email'";
        $result_verify_email = mysqli_query($dbc, $query_verify_email);
        if (!$result_verify_email) { //if the Query Failed ,similar to if($result_verify_email==false)
            echo ' Database Error Occured ';
        }

        if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .

            // Create a unique  activation code:
            $activation = md5(uniqid(rand(), true));

            $query_insert_user =
                "INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";

            $result_insert_user = mysqli_query($dbc, $query_insert_user);
            if (!$result_insert_user) {
                echo 'Query Failed ';
            }

            if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.

                // Send the email:
                $message = " To activate your account, please click on this link:\n\n";
                $message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
                mail($Email, 'Registration Confirmation', $message, 'From:'.EMAIL);

                // Flush the buffered output.

                // Finish the page:
                echo '<div class="success">Thank you for
registering! A confirmation email
has been sent to ' . $Email .
                    ' Please click on the Activation Link to Activate your account </div>';

            } else { // If it did not run OK.
                echo '<div class="errormsgbox">You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
            }

        } else { // The email address is not available.
            echo '<div class="errormsgbox" >That email
address has already been registered.
</div>';
        }

    } else { //If the "error" array contains error msg , display them

        echo '<div class="errormsgbox"> <ol>';
        foreach ($error as $key => $values) {

            echo '	<li>' . $values . '</li>';

        }
        echo '</ol></div>';

    }

    mysqli_close($dbc); //Close the DB Connection

} // End of the main Submit conditional.

Step 4 : Activation Page

This Page contains code that will activate  the new member’s account. This will verify the Activation key in the Activation url against the key in the Database,  if there is a match, the Database field “Activation” is set to NULL. .A Message informing the user that his or her account has been created successfully.


include ('database_connection.php');
if (isset($_GET['email']) && preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/',
 $_GET['email'])) {
 $email = $_GET['email'];
}
if (isset($_GET['key']) && (strlen($_GET['key']) == 32))
 //The Activation key will always be 32 since it is MD5 Hash
 {
 $key = $_GET['key'];
}

if (isset($email) && isset($key)) {

 // Update the database to set the "activation" field to null

 $query_activate_account = "UPDATE members SET Activation=NULL WHERE(Email ='$email' AND Activation='$key')LIMIT 1";
 $result_activate_account = mysqli_query($dbc, $query_activate_account);

 // Print a customized message:
 if (mysqli_affected_rows($dbc) == 1) //if update query was successfull
 {
 echo '<div>Your account is now active. You may now <a href="login.php">Log in</a></div>';

 } else {
 echo '<div>Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';

 }

 mysqli_close($dbc);

} else {
 echo '<div>Error Occured .</div>';
}

Step 4 :Login Page

The Code below handle the Login form.  If there is a match record in the database, a session is created and the member is redirected to page.php .


<form action="login.php" method="post">
 <fieldset>
 <legend>Login Form  </legend>

 <p>Enter Your username and Password Below  </p>

 <div>
 <label for="name">Email :</label>
 <input type="text" id="e-mail" name="e-mail" size="25" />
 </div>

 <div>
 <label for="Password">Password:</label>
 <input type="password" id="Password" name="Password" size="25" />
 </div>
 <div>
 <input type="hidden" name="formsubmitted" value="TRUE" />
 <input type="submit" value="Login" />
 </div>
 </fieldset>
</form>

PHP Code to Handle the Login Form Submission

The code below contains basic validation as follows :

  • Check if both field is empty.
  • Check if email is in correct format using regular expression.

include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
 // Initialize a session:
session_start();
 $error = array();//this aaray will store all error messages

 if (empty($_POST['e-mail'])) {//if the email supplied is empty
 $error[] = 'You forgot to enter  your Email ';
 } else {

 if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
 $Email = $_POST['e-mail'];
 } else {
 $error[] = 'Your EMail Address is invalid  ';
 }
}

if (empty($_POST['Password'])) {
 $error[] = 'Please Enter Your Password ';
 } else {
 $Password = $_POST['Password'];
 }

 if (empty($error))//if the array is empty , it means no error found
 {
$query_check_credentials = "SELECT * FROM members WHERE (Email='$Email' AND password='$Password') AND Activation IS NULL";
 $result_check_credentials = mysqli_query($dbc, $query_check_credentials);
 if(!$result_check_credentials){//If the QUery Failed
 echo 'Query Failed ';
 }

 if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
 { // A match was made.

 $_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);

//Assign the result of this query to SESSION Global Variable

 header("Location: page.php");

 }else
 { $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
 }
}  else {
 echo '<div> <ol>';
 foreach ($error as $key => $values) {
 echo '    <li>'.$values.'</li>';
}
 echo '</ol></div>';
}
 if(isset($msg_error)){
 echo '<div>'.$msg_error.' </div>';
 }
 /// var_dump($error);
 mysqli_close($dbc);
} // End of the main Submit conditional.

Step 5 : Member Section Page

After Login successfully ,The new member will be redirected to page.php .

ob_start();
session_start();
if(!isset($_SESSION['Username'])){
header("Location: login.php");
}

?>
<div class="success">Welcome , $_SESSION['Username']</div>

You can download the complete source code below . Please make the appropriate changes in the database_connection.php file .

Email : test@youhack.net , Password : 1

Related Posts

  1. Username Availability Check in Registration Form using Jquery/PHP
  2. Create your own Error Handler in PHP
  3. An in-depth overview of PHP And Curl
  4. Create fancy contact form with CSS 3 and jQuery
  5. Integrate Login system with Yahoo Connect using Oauth

{ 1 trackback }

An in-depth overview of PHP And Curl
August 7, 2010 at 10:04 pm

{ 89 comments… read them below or add one }

Taisha Schaf October 29, 2011 at 1:27 pm

thanks for the good work

Reply

Shashank November 15, 2011 at 8:03 pm

@Li & @Hyder

Im getting the same error. imean to say i get everything correct till getting the verification link…

But the link has “%40″ instead of the “@” sign in emailid part also i tried manually editing that in the address bar and it shows “ACCOUNT SUCCESSFULLY VERIFIED. PLEASE LOGIN” but wen i try to login it shows “Email eith Inactive or has not been verified”

Also m executing the script on a subdomain of my website, so in the verification link i get “localhost” instead of the website URL part at the begining of the verification link

Please help i m in urgent need of this script..

N hyder bro u r gr8!! Thanx a ton to you man!! You Rock!

Reply

Adrian April 17, 2012 at 10:06 am

try to verify the database password varchart and modify it from 10 to 40

Reply

breakforce December 18, 2011 at 1:28 pm

And how will this be code MySQL

$query_verify_email = “SELECT * FROM members WHERE Email =’$Email’”;
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ‘ Database Error Occured ‘;
}

if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .

// Create a unique activation code:
$activation = md5(uniqid(rand(), true));

$query_insert_user = “INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( ‘$name’, ‘$Email’, ‘$Password’, ‘$activation’)”;

$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo ‘Query Failed ‘;
}

if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.

// Send the email:
$message = ” To activate your account, please click on this link:\n\n”;
$message .= WEBSITE_URL . ‘/activate.php?email=’ . urlencode($Email) . “&key=$activation”;
mail($Email, ‘Registration Confirmation’, $message, ‘From: ismaakeel@gmail.com‘);

Reply

qianhui January 28, 2012 at 6:22 pm

Hi,

I’ve 2 problems with the codes:(

Firstly, whenever i tried loggin in, theres are these “Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at /home/kusiosg/public_html/login.php:10) in /home/kusiosg/public_html/login.php on line 140″ and “Warning: Cannot modify header information – headers already sent by (output started at /home/kusiosg/public_html/login.php:10) in /home/kusiosg/public_html/login.php on line 189
” showing on top of the login box.
I have tried solving it multiple times but still can’t be solved.

Another problem is that i have already changed the email to my own email as well as changed the SMTP (i do have the hosting service), however the sender mail is still default(ismaakeel@gmail.com).

Please reply asap:(
thanks in advance!

Reply

qianhui January 28, 2012 at 6:47 pm

Oh, i have solved the second problem!:) please help me with the first problem! thanks!:D

Reply

divyang February 1, 2012 at 6:39 pm

what will be the code if a unregister user is trying to see the page and i want to rediect him to loging page can u plz help me

Reply

divyang February 1, 2012 at 6:42 pm

and ya i have made a logout page as it was show in comment plzz help me as soon as u can i will be waiting for ur reaply

Reply

Prodyot February 3, 2012 at 5:50 pm

Superb tutorial.
I was tempted to enter an irregular email address while writing this post- but then I decided otherwise :)
Thanks for the post.

Reply

Jude February 5, 2012 at 11:16 am

im still not getting any email confirmation to activate my account.. why do you is the problem? Please help me.. Im stuck…

Reply

Djordje February 8, 2012 at 6:48 pm

Hi, i am not geting email confirmation from your script. First time it come but second no!

Reply

root February 10, 2012 at 11:16 pm

Mantabz..!! from Indonesia..

Reply

smith February 24, 2012 at 5:34 pm

i get this…sombody plz help….

Warning: mail() [function.mail]: Failed to connect to mailserver at “mail.myt.mu” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:\xampp\htdocs\Myfirstwebsite\index.php on line 69

Reply

Adrian April 17, 2012 at 10:04 am

hello, i think you can find some help here

http://www.apachefriends.org/f/viewtopic.php?f=4&t=41901

have a nice day

Reply

Shashank March 4, 2012 at 2:12 pm

Hello Hyder,
I am able to install your code successfully on my web server. Also I have successfully edited my SMTP server address (as provided by my host) in the config file but still i am unable to get the confirmation email. I have also tried deleting that SMTP code line as well as changing it to POP3 & IMAP but nothing seems to work uptil now. Rest everything is working absolutely fine!

Also is there any way to contact you for my project? I have a similar project in which I would like to get your help. Please reply at your earliest as I am really in need of a great programmer like you. Thank you!

Reply

sridhar March 7, 2012 at 12:35 pm

Hello Hyder
am getting this error

( ! ) Warning: mail() [function.mail]: SMTP server response: 550 Access denied – Invalid HELO name (See RFC2821 4.1.1.1) in C:\wamp\www\index.php on line 69
please help me

Reply

abhishek March 12, 2012 at 4:47 pm

hi hyder
i wanna ask that how to avoid same username!!!

Reply

RevJoe March 18, 2012 at 1:15 am

Hey, can someone help me with a problem. When I get the activation mail, the sender is the one who posted this code. I wanna change it to my own emailaddress. And another thing, after activating, it gives me the error code. Can someone help me with that?

Reply

anshu March 19, 2012 at 12:06 pm

Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:\xampp\htdocs\php_reg\index.php on line 69

i got error like that … but database has been updated… kindly suggest me any solution please…

Reply

Adrian April 17, 2012 at 10:00 am

i think you need to unlok your port 25 SMTP, it is a email problem, as i see u are using xampp, try and use a real webserver FTP

Reply

Adrian April 17, 2012 at 10:04 am

here , i think you can find some help

http://www.apachefriends.org/f/viewtopic.php?f=4&t=41901

have a nice day

Reply

nicky March 30, 2012 at 1:03 pm

how to change %40 to @?
it’s very hard to see and what will change
please help me bro..

Reply

Adrian April 17, 2012 at 9:10 am

Hello Hyder, please can someone tell me f i want the form also emailed with the activation link how can i do that?

So the email will show the activation link + info from the form such as , email, name and so on.

Thank you :)

Reply

Adrian April 17, 2012 at 1:32 pm

i rezolved this, thank you

Reply

debier April 17, 2012 at 11:13 am

Thx for the script easy to get it working.
Maybe its its a good idea to also have a simple anti-spam form integrated in the activation page.

Reply

Leave a Comment

Previous post:

Next post: