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 }

sergio July 13, 2010 at 10:53 am

hi there
this looks a very good script but i can’t install in remote because this value
date_default_timezone_set is in error and i can’t continue.

if i try to comment i see a blank page.

could you help me to fix it?
thanks in advance

Reply

Hyder July 26, 2010 at 4:14 pm

Which error are you getting sergio ?

Reply

Mike August 8, 2010 at 2:59 pm

Hello Hyder,
The script is really nice but its buggy. If you hit refresh in your browser after registering you will get duplicate entries in the database along with a host of errors in the login process because of this. Something like this might help :

$email=mysql_real_escape_string($_POST['email']);

$sql = “SELECT email FROM users WHERE email = ‘”.$email.”‘”;
$res = mysql_query($sql);

if(mysql_num_rows($res) < 1)
{

// email address is not in database
etc etc …..

Thanks for the tutorial

Reply

Mike August 8, 2010 at 6:49 pm

apologies Hyder. I’ve rechecked the code. the error stems from the VARCHAR lenght for the Email. 20 chars is a bit too short and the remainder gets sliced of which makes it impossible for mysql to match them. You should mention this in your tutorial

cheers

Reply

Lawrence October 5, 2010 at 11:01 am

Hello Hyder

I get to have the same issue of inserting same value in the db after hitting on the refresh button on the browser, pls can you help out!
cheers

Reply

Edwin Evans December 1, 2010 at 8:03 pm

It should encrypt the password.

Reply

alex December 3, 2010 at 6:47 pm

can tou help me with a logout script to or, something like logout if you are inactive after 3 minutes. Thanks.

Reply

manju December 8, 2010 at 3:47 pm

sorry how to forget password plz help me

Reply

manju December 8, 2010 at 3:49 pm

sorry were user name email passwords store plz help me

Reply

philip January 5, 2011 at 4:33 pm

i got the following error how do i solve this ? thnaks

Database Error Occured
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampplite\htdocs\coolmovies\new email validation\ndex.php on line 48
Query Failed

Reply

vivek January 29, 2011 at 6:06 am

HI……
The code i have read her is really awosome.
Thanks…….

Reply

Enthony March 2, 2011 at 10:41 pm

is it safe from MySQL injection?

Reply

Hyder March 7, 2011 at 1:51 pm

I received your mail Enthony .Yes , it is safe from SQL Injection . If you want to encrypt password use the built-in Function MD5() or SHA1() .
Example :
MD5($password) ;
However , MD5 and SHA1 is crackeable by bruteforce . If you want a more secure hash algorithm you might think of generating something like :

SHA1(MD5($password.$password)) ; // concatenation of plain password,then hash it in md5 , then hash the md5 in sha1 algorithm

Let me know , if you need more clarification .

Reply

jamie September 16, 2011 at 5:05 pm

Hello! Sorry if i ask to many questions but… I am semi new at all this php/mysql stuff.

I got your code to work awesomely but i would love to encrypt the password, where exactly in the code do i do that?

Reply

Hyder September 16, 2011 at 8:24 pm

replace $password with md5($password)

Reply

Omar Ali January 16, 2012 at 4:13 am

As salaam alaikum Hyder!

This is your new brother Omar, I just want to say thanks a lot for the wonderful code. I am using your code and I really want to thank you so much for helping everyone ok? Please let me know if you ever need anything alright. take care and we should stay in touch

Reply

Hyder January 16, 2012 at 5:45 am

walaikumsalam . i’m glad my code helped you :)

nicky March 31, 2012 at 5:45 am

how to change %40 to @ sign?
i cant find where to change

Reply

Enthony March 7, 2011 at 6:51 pm

Hi again :),

I use your registration script in popup window, how to to check logged in user for whole document? how to get his name?

Reply

Enthony March 8, 2011 at 5:18 pm

How to add comments after each text like in your’s site?

Reply

Robert March 23, 2011 at 6:41 pm

this is exactly what i have been looking for!!
i only have one problem and that the email validation i dont know where to get all the info to fill in (
/*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’, ‘ismaakeel@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’);)
)

please could someone help and one other thing can someone tell me if the email validation will still work if im using a localhost (xampp)

Thanks
Robert

Reply

Hyder March 23, 2011 at 6:54 pm

You need a smtp server address to be able to send mail . You may google for one free smtp server and insert it there if you do not have a web hosting account . If you are using Xampp , i guess it comes with Mercury which is a mail server . I have tried to configure it in the past but in vain . :) Try googling for a tutorial how to use mercury to be able to send mail .
Hyder .

Reply

mike April 14, 2011 at 1:09 pm

I think this is a great script, and I like it very much. I’ve been trying to learn PHP, and I seem to be running into a problem with this script. Will someone please try to explain what I am doing wrong and how I can fix this problem?

When I fill out the form,” name, email and password”, and press submit, the input information does go to the database and I get a confirmation notice.

Thank you for registering! A confirmation email has been sent to john@gmail.com Please click on the Activation Link to Activate your account

http://www.yourdomain.com/test/activate.php?email=john112%40gmail.com&key=db872e76255db2f62cce5bf794279e0e

When I press on the activation account I get this?

Oops !Your account could not be activated. Please recheck the link or contact the system administrator.

Will someone please try to explain what I am doing wrong and how I can fix this problem?
in this comment I did change the “email address and i put yourdomain” but in the test scrip it has the correct information.
Thank you.

Reply

Omer January 17, 2012 at 4:01 am

you need to change the char in the activation sql table to be more than just 20 or 30 char limit… do something like 300 or more….

Reply

maryam May 4, 2011 at 12:26 pm

hi,thanks for your code
i used your code in my site, but the problem is that after registering no email will be sent to users.after registering the message(Thank you for registering! A confirmation email has been sent to….)is shown but no email is sent.I think the problem is with this part ,but i dont know how to correct it.:
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.

$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);

echo ‘Thank you for registering! A confirmation email has been sent to ‘ . $Email . ‘ Please click on the Activation Link to Activate your account ‘;

Reply

tommy May 21, 2011 at 11:38 pm

Can any one help me with the script that echo variables on a successful page. e.g. register.php and it will echo than you $fname your registration is successful and a confirmation code have been sent to tommy@yahoo.com

Reply

pankaj June 19, 2011 at 10:49 am

Warning: mail() [function.mail]: SMTP server response: 550 No such user here in C:\inetpub\vhosts\dost2web.com\httpdocs\test\pankaj\index.php on line 69
http://test.dost2web.com/pankaj/index.php
i am getting this error.so please give me solutions

Reply

Hyder June 19, 2011 at 11:11 am

@Pankaj : The problem seems to lie with your smtp server settings

Reply

pankaj June 19, 2011 at 1:06 pm

can u suggest me what & where i have to change smtp server setting.

Reply

A P June 20, 2011 at 7:22 pm

I keep getting this error as soon as I go on the register page:

Could not connect to MySQL: Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock

I downloaded your source files so besides setting the stuff in database_connection.php to my own it is not edited,,, please help!!

Reply

Hyder June 20, 2011 at 8:30 pm

@Pankaj : You seem to be using windows server . This link should help you configure your smtp to be able to send mail .
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/e4cf06f5-9a36-474b-ba78-3f287a2b88f2.mspx?mfr=true
But for me the best solution would be to buy a cheap linux hosting.This will save you the hassle to configure and tweak the microsoft products ! :)

@AP : what environment are you using ? is it hosted on your pc ? are you using xampp/lampp ? usually you get this error because Mysql is not running.have you tried to restart MYSQL ?

Reply

Rajim Laymond June 24, 2011 at 6:06 am

Great Tutorial, two thumbs!
Pardon, can you please assist me to create a logout code and destroy session
Thank’s in advance :)

Reply

Rajim Laymond June 24, 2011 at 6:21 am

code above work, but would you please review or give suggestion :)

Reply

Hyder June 24, 2011 at 8:19 am

@Rajim : Eit Page.php to add a logout link as below :

echo '<div class="success">Welcome ,' . $_SESSION['Username'] .'<a href="logout.php"></a></div>';

Create a logout.php page and add the code below :

if(isset($_SESSION['Username'])){//if user session exists
    unset($_SESSION);//destroy all sessions
	header("Location: login.php");//redirect to login page
	}

I have not tested the code , let me know if you have any issue

Reply

Aaron July 1, 2011 at 8:50 am

am using xampp 1.6.4 and have tried to edit the php.ini form inorder to send mails in the registration form but am getting the same error ‘Failed sending registration confirmation email’.

Reply

Hyder July 1, 2011 at 9:42 am

@Aaron : Editing php.ini is not enough . You need to configure Mercury mail server ( which comes bundled in XAMMP .You can find a bunch of tutorial of youtube to get this working :
http://www.youtube.com/watch?v=zO2p3uX9poY
or look on google how to configure mercury mail.In my case , i’m simply using an external smtp server . :)

Reply

Rajim Laymond July 3, 2011 at 6:55 pm

Thank you very much and pardon for asking again.
I want signature available on email verification, i did trial and error, mostly error :)
Need to customize original code below
// 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‘);
// Flush the buffered output.

Can you please assist or paste here custom code :)

Reply

Hyder July 3, 2011 at 7:29 pm

@Rajim : what do you mean by signature ? can you explain in much more detail what you want exactly ?

Reply

Rajim Laymond July 4, 2011 at 4:44 am

@Hyder,
What i mean is my name available at bottom and company logo at top of email.
Below is the sequence.

logo (jpg, png or gif picture) // i need this

Hello Sir/Madam,
Thank you for registering………., to activate your account, please click on this link…….

Best regards, // i need this
Rajim

Reply

Sean July 4, 2011 at 6:12 am

Hi Hyder, Great code, works perfect. Could you guide me on how to add a password recovery option? Thanks in advance.

-Sean

Reply

Travis July 6, 2011 at 2:09 am

on line 48 on index.php
if (mysqli_num_rows($result_verify_email) == 0)
error is caused by the 0 the error message on the page using the downloaded source code
is
“Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /www/zxq.net/s/t/o/storgeio/htdocs/PHPRF/index.php on line 48
Query Failed”

any help would be greatly appreciated
thanks in advance

Reply

jackie August 16, 2011 at 11:02 am

hey when i download ur file n try they giv me this,

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\mp_elearning\elearning\register\index.php on line 69

was wondering wads wrong after i register?
really need ur help i need to try out n implement it on my major project for my final year ):
help would be deeply appreciated thx!

Reply

Hyder August 16, 2011 at 11:10 am

your xampp is not configured to send mail . The script is trying to connect to a smtp server to send mail.
solution 1 : edit the php file or php.ini to add an external smtp server address. ( best one in my opinion )
solution 2 : configure your xampp to be able to send mail , i think you need to tweak mercury mail which come bundled with xampp .
solution 3 : disable completely the ’sending mail feature’ in the php file . let me know if you need ayn clarification :)

Reply

jackie August 17, 2011 at 2:09 am

i have download the free smtp server,
i have modify this
/*You might not need this */
ini_set(‘SMTP’, “mail.myt.mu”); // Overide The Default Php.ini settings for sending mail

to this

ini_set(‘SMTP’, “localhost”); // Overide The Default Php.ini settings for sending mail

wad do u mean by editing the php file or php.ini?
sry im new to this ):

Reply

jackie August 17, 2011 at 2:32 am

hey hyder i got the email verification working! (:
however, when i go to my email n copy the activation key, n try to access it says object couldnt be found hmm..

Reply

jackie August 17, 2011 at 2:42 am

hey hyder lets say i wanna add the senidng of verifying email to my codes where should i add it in n which part of ur code?

my code is as below

Registration

Welcome to Finance Is Fun Registration Page

Registration Page

Thank you for your visit! Please register with us to get notifications of updates with us.

<?php

$submitted = isset($_POST['submit']);
$success = FALSE;

//TODO check $submitted and blank fields
if ($submitted) {

// check if $_POST['name'] is empty and strip any slashes if not
if (!empty($_POST['name'])) {
$name=$_POST['name'];
} else {
$name=NULL;
echo 'You forgot to enter your name!’;
}

// check if $_POST['sex'] is empty and strip any slashes if not
if (!empty($_POST['sex'])) {
$sex=stripslashes($_POST['sex']);
} else {
$sex=NULL;
echo ‘You forgot to enter your sex!’;
}

// check if $_POST['email'] is empty and strip any slashes if not
if (!empty($_POST['email'])) {
$email=stripslashes($_POST['email']);
} else {
$email=NULL;
echo ‘You forgot to enter your email!’;
}

if (!empty($_POST['password'])) {
$password=stripslashes($_POST['password']);
} else {
$password=NULL;
echo ‘You forgot to enter a password!’;
}

// check if $_POST['contactno'] is empty and strip any slashes if not
if (!empty($_POST['contactno'])) {
$contactno=stripslashes($_POST['contactno']);
} else {
$contactno=NULL;
echo ‘You forgot to enter your contact number!’;
}

// check if user selected a salarayrange in the dropdownlists.
if (!empty($_POST['salaryrange'])) {
$salaryrange=stripslashes($_POST['salaryrange']);
} else {
$salaryrange = NULL;
echo ‘You forgot to select your salaryrange!’;
}

// if all data entered, display a message
if ($name && $sex && $email && $password && $contactno && $salaryrange)
{

//TODO 1: Connect to forumdb Database
$mysqli = new mysqli(“localhost”, “root”, null, “forumdb”);

//TODO 2: Prepare the Insert Statement
$stmt = $mysqli->prepare(“INSERT INTO user
(email, password, name, gender, contactno, salaryrange)
VALUES (?,?,?,?,?,?)”);

//TODO 3: Bind the values
$stmt->bind_param(“ssssss”, $email, $password, $name, $sex, $contactno, $salaryrange);

//TODO 4: Execute the statement
$result = $stmt->execute();

//TODO 5: Set $success=TRUE & print data if save is successful,
// Otherwise set $success=FALSE and print error message
if ($result) {
$success = TRUE;
echo ‘Thank you’;
echo “Thank you, $name. You entered your the following details : “;
echo ”;
echo “Sex: $sex “;
echo “Email: $email “;
echo “Contact Number: $contactno “;
echo ”;
// print each interest in the array using foreach loop
echo ”;
echo “Salary Range: $salaryrange “;
echo ”;
echo ‘Go to Login‘;
echo ‘Verify Email‘;
}
else{
$success = FALSE;
echo “Registration not successful”;
}

//TODO 6: Close SQL statement
$stmt->close();

//TODO 7: Close database connection
$mysqli->close();

} else {
// at least one form element was not filled out properly
echo ‘Please go back and fill out the form again.‘;
}

}

if ($success == FALSE) {
?>

Enter your information in the form below:

Name:
<input type="text" name="name" size="20" maxlength="40" value="”/>

Sex:
<input type="radio" name="sex" value="Male" /> Male
<input type="radio" name="sex" value="Female" /> Female

Email:
<input type="text" name="email" size="20" maxlength="80" value="” />

Password:

Contact Number:
<input type="text" name="contactno" size="10" maxlength="15" value="” />

Salary Range:

–Please select–
<option value="$0-$1000">$0-$1000
<option value="$1000-$2000">$1000-$2000
<option value="$2000-$3000">$2000-$3000
<option value="$3000-$4000">$3000-$4000
<option value="$4000-$5000">$4000-$5000
<option value="Above $5000">Above $5000

Copyright 2011 by Finance Is Fun Pte Ltd.   All rights reserved.

Reply

jamie September 13, 2011 at 11:13 pm

Hey I am getting the same error as Travis

“Database Error Occured
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/idgstage/public_html/autobuy365/register/index.php on line 48
Query Failed”

if anyone could offer any help that would be great!

Reply

jamie September 14, 2011 at 7:36 pm

i have run into another error. i fixed the above mentioned error however now I am getting a error when trying to verify my email. “Oops !Your account could not be activated. Please recheck the link or contact the system administrator.”

if someone can please help me that would be awesome.

Reply

Hyder September 14, 2011 at 8:03 pm

For some reasons,the update query :

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

Could not be run successfully . After clicking the activation link,check manually in the database if it has been updated or not ? It’s possible also that there’s 2 identical email in the db.try empty your DB and retry again .Let me know if 1 of these 2 solutions solve the issue ?

Reply

jamie September 14, 2011 at 8:41 pm

i found an error with the emailadress row in the database. it is set to varchar(20) and my email address is 25 characters. i changed the 20 to 40 and that fixed the problem that i can see. thank you for the reply!

Reply

Li October 24, 2011 at 2:56 pm

Tried your solution…still not working. After clicking the activation link, the database, or activation area remains the same as before clicking. No identical emails. Any other ideas?

Reply

vir0e5 September 17, 2011 at 4:42 am

nice code… i need for back end and super administrator for control to activation member..not to email!!

Reply

swathi September 17, 2011 at 11:48 am

hello ,

I was worked with ur demo but page not found only displayed…

Reply

Harish October 4, 2011 at 5:28 pm

please tell me how to upload this file to cpanel and what about localhost…..

can u please write configure for cpanel phpmyadmin

Reply

Chand October 8, 2011 at 2:07 pm

I am not getting email verification,
smtp server config could not be understood and should the email address to be related with smtp server,
kindly help,
suggest free smtp server

Reply

David October 12, 2011 at 11:52 pm

Hi everyone,
I cannot get the activation code. I get the following message: Error Occurred
Can someone help>
Thanks.
Dave

Reply

lolo October 16, 2011 at 6:38 am

Hello Hyder,
The script is really nice. i have run into another error

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first. z1sm43381579pbl.5 in C:\xampp\htdocs\test\index.php on line 69

any help would be greatly appreciated
thanks in advance

Reply

lolo October 17, 2011 at 11:14 am

Hello Hyder,
i got the email verification working thanks

Reply

sridhar March 7, 2012 at 12:41 pm

how did you solve the please help me

Reply

Maria October 23, 2011 at 2:42 pm

I receive the following error: Failed sending registration confirmation email.
I use XAMPP-win32-1.7.7.
Apache/2.2.21
Help me please
Thanks!

Reply

Li October 24, 2011 at 2:49 am

Thanks for this! Everything is working great EXCEPT the email verification link reads:

http://www.mywebsite.com/activate.php?email=myemail%40yahoo.com&key=db05e0e346d49d0d8a162f0be012c168

notice the @yahoo.com is replaced with %40yahoo.com

Any idea why?

Reply

Li October 24, 2011 at 2:58 am

Fixed the above error but still getting this when clicking on activation link:

Oops !Your account could not be activated. Please recheck the link or contact the system administrator.

What causes this? Cannot find the error.

Reply

Rahul December 4, 2011 at 9:23 am

Same problem with me as well :(
Please suggest some way out

Reply

SkalaIbitol December 19, 2011 at 9:14 pm

I found out that email column in database was too narow (20) and m from .com was missing. Just set email column in members table to 30 and test it. That saved my day :)

Reply

Leave a Comment

Previous post:

Next post: