top
logo


Building A registration System with Email verification in PHP PDF Печать E-mail
Автор: adm   
04.04.13 13:25
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

  • 360

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.

01 <?php
02
03 /*Define constant to connect to database */
04 DEFINE('DATABASE_USER', 'root');
05 DEFINE('DATABASE_PASSWORD', '');
06 DEFINE('DATABASE_HOST', 'localhost');
07 DEFINE('DATABASE_NAME', 'forum');
08 /*Default time zone ,to be able to send mail */
09 date_default_timezone_set('UTC');
10
11 /*You might not need this */
12 ini_set('SMTP', "mail.myt.mu");
13 // Overide The Default Php.ini settings for sending mail
14
15 //This is the address that will appear coming from ( Sender )
16 define('EMAIL', ' Данный адрес e-mail защищен от спам-ботов, Вам необходимо включить Javascript для его просмотра. ');
17
18 /*Define the root url where the script will be found such as
20 DEFINE('WEBSITE_URL', 'http://localhost');
21
22 // Make the connection:
23 $dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
24 DATABASE_NAME);
25
26 if (!$dbc) {
27 trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
28 }
29
30 ?>

Database Structure

01 --
02 -- Table structure for table `members`
03 --
04
05 CREATE TABLE IF NOT EXISTS `members` (
06 `Memberid` int(10) NOT NULL AUTO_INCREMENT,
07 `Username` varchar(20) NOT NULL,
08 `Email` varchar(20) NOT NULL,
09 `Password` varchar(10) NOT NULL,
10 `Activation` varchar(40) DEFAULT NULL,
11 PRIMARY KEY (`Memberid`)
12 ) 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 .

01 <form action="index.php" method="post" class="registration_form">
02 <fieldset>
03 <legend>Registration Form </legend>
04
05 <p>Create A new Account <span style="background:#EAEAEA none repeat scroll 0 0;line-height:1;margin-left:210px;;padding:5px 7px;">
06 Already a member? <a href="login.php">Log in</a></span> </p>
07
08 <div class="elements">
09 <label for="name">Name :</label>
10 <input type="text" id="name" name="name" size="25" />
11 </div>
12 <div class="elements">
13 <label for="e-mail">E-mail :</label>
14 <input type="text" id="e-mail" name="e-mail" size="25" />
15 </div>
16 <div class="elements">
17 <label for="Password">Password:</label>
18 <input type="password" id="Password" name="Password" size="25" />
19 </div>
20 <div class="submit">
21 <input type="hidden" name="formsubmitted" value="TRUE" />
22 <input type="submit" value="Register" />
23 </div>
24 </fieldset>
25 </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= Данный адрес e-mail защищен от спам-ботов, Вам необходимо включить Javascript для его просмотра. &key=c47662ba2504508bcdd5cb75106110a6

01 include ('database_connection.php');
02 if (isset($_POST['formsubmitted'])) {
03 $error = array(); //Declare An Array to store any error message
04 if (empty($_POST['name'])) { //if no name has been supplied
05 $error[] = 'Please Enter a name '; //add to array "error"
06 } else {
07 $name = $_POST['name']; //else assign it a variable
08 }
09
10 if (empty($_POST['e-mail'])) {
11 $error[] = 'Please Enter your Email ';
12 } else {
13
14 if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",
15 $_POST['e-mail'])) {
16 //regular expression for email validation
17 $Email = $_POST['e-mail'];
18 } else {
19 $error[] = 'Your EMail Address is invalid  ';
20 }
21
22 }
23
24 if (empty($_POST['Password'])) {
25 $error[] = 'Please Enter Your Password ';
26 } else {
27 $Password = $_POST['Password'];
28 }
29
30 if (empty($error)) //send to Database if there's no error '
31
32 { // If everything's OK...
33
34 // Make sure the email address is available:
35 $query_verify_email = "SELECT * FROM members  WHERE Email ='$Email'";
36 $result_verify_email = mysqli_query($dbc, $query_verify_email);
37 if (!$result_verify_email) { //if the Query Failed ,similar to if($result_verify_email==false)
38 echo ' Database Error Occured ';
39 }
40
41 if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
42
43 // Create a unique  activation code:
44 $activation = md5(uniqid(rand(), true));
45
46 $query_insert_user =
47 "INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";
48
49 $result_insert_user = mysqli_query($dbc, $query_insert_user);
50 if (!$result_insert_user) {
51 echo 'Query Failed ';
52 }
53
54 if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
55
56 // Send the email:
57 $message = " To activate your account, please click on this link:\n\n";
58 $message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
59 mail($Email, 'Registration Confirmation', $message, 'From:'.EMAIL);
60
61 // Flush the buffered output.
62
63 // Finish the page:
64 echo '<div class="success">Thank you for
65 registering! A confirmation email
66 has been sent to ' . $Email .
67 ' Please click on the Activation Link to Activate your account </div>';
68
69 } else { // If it did not run OK.
70 echo '<div class="errormsgbox">You could not be registered due to a system
71 error. We apologize for any
72 inconvenience.</div>';
73 }
74
75 } else { // The email address is not available.
76 echo '<div class="errormsgbox" >That email
77 address has already been registered.
78 </div>';
79 }
80
81 } else { //If the "error" array contains error msg , display them
82
83 echo '<div> <ol>';
84 foreach ($error as $key => $values) {
85
86 echo '  <li>' . $values . '</li>';
87
88 }
89 echo '</ol></div>';
90
91 }
92
93 mysqli_close($dbc); //Close the DB Connection
94
95 } // 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.

01 include ('database_connection.php');
02 if (isset($_GET['email']) && preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/',
03 $_GET['email'])) {
04 $email = $_GET['email'];
05 }
06 if (isset($_GET['key']) && (strlen($_GET['key']) == 32))
07 //The Activation key will always be 32 since it is MD5 Hash
08 {
09 $key = $_GET['key'];
10 }
11
12 if (isset($email) && isset($key)) {
13
14 // Update the database to set the "activation" field to null
15
16 $query_activate_account = "UPDATE members SET Activation=NULL WHERE(Email ='$email' AND Activation='$key')LIMIT 1";
17 $result_activate_account = mysqli_query($dbc, $query_activate_account);
18
19 // Print a customized message:
20 if (mysqli_affected_rows($dbc) == 1) //if update query was successfull
21 {
22 echo '<div>Your account is now active. You may now <a href="/login.php">Log in</a></div>';
23
24 } else {
25 echo '<div>Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';
26
27 }
28
29 mysqli_close($dbc);
30
31 } else {
32 echo '<div>Error Occured .</div>';
33 }

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 .

01 <form action="login.php" method="post">
02 <fieldset>
03 <legend>Login Form  </legend>
04
05 <p>Enter Your username and Password Below  </p>
06
07 <div>
08 <label for="name">Email :</label>
09 <input type="text" id="e-mail" name="e-mail" size="25" />
10 </div>
11
12 <div>
13 <label for="Password">Password:</label>
14 <input type="password" id="Password" name="Password" size="25" />
15 </div>
16 <div>
17 <input type="hidden" name="formsubmitted" value="TRUE" />
18 <input type="submit" value="Login" />
19 </div>
20 </fieldset>
21 </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.
01 include ('database_connection.php');
02 if (isset($_POST['formsubmitted'])) {
03 // Initialize a session:
04 session_start();
05 $error = array();//this aaray will store all error messages
06
07 if (empty($_POST['e-mail'])) {//if the email supplied is empty
08 $error[] = 'You forgot to enter  your Email ';
09 } else {
10
11 if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
12 $Email = $_POST['e-mail'];
13 } else {
14 $error[] = 'Your EMail Address is invalid  ';
15 }
16 }
17
18 if (empty($_POST['Password'])) {
19 $error[] = 'Please Enter Your Password ';
20 } else {
21 $Password = $_POST['Password'];
22 }
23
24 if (empty($error))//if the array is empty , it means no error found
25 {
26 $query_check_credentials = "SELECT * FROM members WHERE (Email='$Email' AND password='$Password') AND Activation IS NULL";
27 $result_check_credentials = mysqli_query($dbc, $query_check_credentials);
28 if(!$result_check_credentials){//If the QUery Failed
29 echo 'Query Failed ';
30 }
31
32 if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
33 { // A match was made.
34
35 $_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
36
37 //Assign the result of this query to SESSION Global Variable
38
39 header("Location: page.php");
40
41 }else
42 { $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
43 }
44 } else {
45 echo '<div> <ol>';
46 foreach ($error as $key => $values) {
47 echo '    <li>'.$values.'</li>';
48 }
49 echo '</ol></div>';
50 }
51 if(isset($msg_error)){
52 echo '<div>'.$msg_error.' </div>';
53 }
54 /// var_dump($error);
55 mysqli_close($dbc);
56 } // End of the main Submit conditional.

Step 5 : Member Section Page

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

1 ob_start();
2 session_start();
3 if(!isset($_SESSION['Username'])){
4 header("Location: login.php");
5 }
6
7 ?>
8 <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 .

 

http://youhack.me/2010/04/01/building-a-registration-system-with-email-verification-in-php/

 
Интересная статья? Поделись ей с другими:

bottom

 

Unreal Commander PfSense по русски Яндекс.Метрика