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

{ 64 comments… read them below or add one }

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

Leave a Comment

Previous post:

Next post: