Email Activation For Registration Forms

Email Activation For Registration Forms

Foreword: There are two good reasons why email activation is a necessary for webmasters. First, it helps root out spam by requiring user interaction. It also creates a sense of trust, since we can build a certain amount of trust with a user who can confirm they are who they say they are. In this example you will need access to a database (MySQL is what we’ll use) with proper permissions.

We’ll start out creating the interface of the form. You will need to create two files: one file to hold the form, the next file to handle the verification process and interface with the database. It doesn’t necessarily matter what you name your files, but to stay uniform with our examples name the registration and verification files register.php and verify.php, respectively.

Below you will see register.php in action- in all its simplistic glory.

Our Registration Form – register.php

<html>
 <body>
  <form action="verify.php" method="post" name="register">
    Username: <input type="text" name="username" />
    Password: <input type="text" name="password" />
    Email: <input type="text" name="email" />
  <input type="submit" />
  </form>
 </body>

</html>

At this point the only things worth mentioning is that we are putting “verify.php” as the form action, and naming the form “register” with the name command. Go ahead and save this file and upload it to your hosting account- we’re done with this file for now.

Groundwork For The Verification Process

Now let’s create a file named verify.php. We are using this file for two things. First, we use it to insert data into the database if everything seems to be hunky-dory. But we also use it to confirm the verification code we email the user, so we’ll need to make use of the “IF” selection structure to differentiate between the two processes.

So how do we know if the verify.php file should submit data to our database or verify the activation code a user provides? We’ll admit that when we said we were done with register.php, we lied. To properly determine if the user is submitting data or verifying a code, we need to add a hidden value on the registration form, as seen below:

Hidden Values For Our Registration Form – register.php

<html>
 <body>
  <form action="verify.php" method="post" name="register">
    Username: <input type="text" name="username" />
    Password: <input type="text" name="password" />
    Email: <input type="text" name="email" />
	<input type="hidden" name="form_submitted" value="1"/> 
  <input type="submit" />
  </form>
 </body>
</html>

Now we can check to see if this value is set on our verify.php file with the following code:

Selection Structure – verify.php

if ($_POST['form_submitted'] == '1') {

## Form was submitted,the user is registering!

 } else{

## No value found, user must be activating their account!

}

With our form and selection structure in place, we need to go to our “backend” and create a database.

Database Design For Email Activation

In our example we are creating a table named “users” with the fields “id, status, username, password, email, and activationkey” – we encourage you to use the same values for the sake of simplicity. In fact, you can just run the SQL query below and do just that:

SQL Query Code – Run Code to Create Table And Fields

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL auto_increment,
  `status` varchar(20) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `email` varchar(20) NOT NULL,
  `activationkey` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `activationkey` (`activationkey`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

If all has gone well, your database should look something like the following (note if you aren’t using PHPMyAdmin and MySQL, you may see some differences):

Inserting Registration Data Into Database With PHP

Now that we have a good grasp on where we are going, we can go ahead and connect to our database. First we’ll need to arrange the correct connection statement. We will be using the mysql_connect and mysql_select_db functions to make the connection to our database.

Connecting To The Database – verify.php

mysql_connect("localhost", DATABASE, PASSWORD or ;die(mysql_error());

mysql_select_db("USER_TABLENAME ") or die(mysql_error());

Above we can see that the only thing we need to change is the database, password, and table name. Ideally the table name should be “users” as per our example. Your password and database name can be created via MySQL if you have the proper permissions. If you don’t, contact your web host to get a database configured.

So far your verify.php should look like this:

Project Thus Far – verify.php

<?php

mysql_connect("localhost", "DATABASE", "PASSWORD") or die(mysql_error());

mysql_select_db("USER_TABLENAME") or die(mysql_error());

if ($_POST['form_submitted'] == '1') {
} else {

}
?>

Test the connection by uploading the file to your server and navigating to the file. If an error doesn’t present itself, it means you successfully connected to your database! (Even if you see a blank page) Now we can create a random key and answer all of the data into our database.

Creating A Random Key And Inserting Database Values

We will be using the mt_rand() function to create our random key. Below you’ll see that we concatenate the function five times in order to get a lengthy string.

Random Number Generator – verify.php

$activationKey =  mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand();

Don’t get too excited to try it out yet, first let’s write the code to insert the value into our database.

Inserting Data Into A Database – verify.php

$sql="INSERT INTO users (username, password, email, activationkey, status) VALUES ('$_POST[username]', '$_POST[password]', '$_POST[email]', '$activationKey', 'verify')";

if (!mysql_query($sql))

  {

  die('Error: ' . mysql_error());

  }

Above you can see we are updating all of the rows with information from our registration field via the $_POST command. We are also including the $activationKey variable and inputting the word ‘verify’ into the status field. This is to keep track of who is verified and who isn’t. If someone isn’t verified yet, but has registered, we could easily have them request to resend the email instead of having to register again. Oh, technology!

So far the code should be as below:

Script Thus Far – verify.php

<?php

mysql_connect("localhost", DATABASE, "PASSWORD") or die(mysql_error());

mysql_select_db("USER_TABLENAME ") or die(mysql_error());

if ($_POST['form_submitted'] == '1') {
##User is registering, insert data until ;we can activate it

$activationKey =  mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand();

$sql="INSERT INTO users (username, password, email, activationkey, status)

VALUES

('$_POST[username]', '$_POST[password]', '$_POST[email]','$activationKey', 'verify')";

if (!mysql_query($sql))

  {

  die('Error: ' . mysql_error());

  }

} else {

}

?>

Sending The Activation Key

Sending an email with PHP is painlessly easy- we just have to supply a few values to an already-made function in PHP: the aptly named mail() command. In our example we are using four parameters to send the email: the recipient address, the subject of the email, the message, and our own return address.

Sending Mail With PHP – verify.php

	echo "An email has been sent to $_POST[email] with an activation key. Please check your mail to complete registration.";

##Send activation Email

$to      = $_POST[email];

$subject = " YOURWEBSITE.com Registration";

$message = "Welcome to our website!rrYou, or someone using your email address, has completed registration at YOURWEBSITE.com. You can complete registration by clicking the following link:rhttp://www.YOURWEBSITE.com/verify.php?$activationKeyrrIf this is an error, ignore this email and you will be removed from our mailing list.rrRegards, YOURWEBSITE.com Team";

$headers = 'From: noreply@ YOURWEBSITE.com' . "rn" .

    'Reply-To: noreply@ YOURWEBSITE.com' . "rn" .

    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

This should be fairly self-explanatory. Notice that we are using the r command to force a return- this is to format the email so all the text isn’t on one line. If you wanted, you could even include HTML and images into the email. We would recommend you didn’t, however, as many mail platforms today either don’t support such features or mark most emails that contain them as spam.

Coding The Verification Checking Process

We have arrived at the final part of this lesson: checking the verification code and allowing the user to either be registered or tell them they have entered the wrong code and to try again. In this section we will actually grab the current URL, take the query string, and then check our database to see if it matches a record. If it does, we will call the registrant a member and remove the key from our database. Otherwise, tough luck!

Script Thus Far – verify.php

##User isn't registering, check verify code and change activation code to null, status to activated on success

$queryString = $_SERVER['QUERY_STRING'];

$query = "SELECT * FROM users";

$result = mysql_query($query) or die(mysql_error());

  while($row = mysql_fetch_array($result)){

    if ($queryString == $row["activationkey"]){

       echo "Congratulations!" . $row["username"] . " is now the proud new owner of a YOURWEBSITE.com account.";

       $sql="UPDATE users SET activationkey = '', status='activated' WHERE (id = $row[id])";

       if (!mysql_query($sql))

  {

        die('Error: ' . mysql_error());

  }

    }

  }

Above we are doing just as we stated. Pay special attention to the fact we are using the UPDATE command in SQL- not INSERT. Also note that we need the while loop to find the exact ID of the member to update- we don’t want to update everyone in our database! We do this by comparing the current record ID with one from the database- and voila! If a match is found, we can update it.

Finally, we need to add some security to our script. Read our SQL Injection Tutorial and add the updates below:

Final Result – verify.php

mysql_connect("localhost", DATABASE, "PASSWORD") or die(mysql_error());

mysql_select_db("USER_TABLENAME") or die(mysql_error());

if ($_POST['form_submitted'] == '1') {
##User is registering, insert data until we can activate it

$activationKey =  mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand();
$username = mysql_real_escape_string($_POST[username]);
$password = mysql_real_escape_string($_POST[password]);

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

$sql="INSERT INTO users (username, password, email, activationkey, status) VALUES ('$username', '$password', '$email', '$activationKey', 'verify')";

if (!mysql_query($sql))

  {

  die('Error: ' . mysql_error());

  }

echo "An email has been sent to $_POST[email] with an activation key. Please check your mail to complete registration.";

##Send activation Email

$to      = $_POST[email];

$subject = " YOURWEBSITE.com Registration";

$message = "Welcome to our website!rrYou, or someone using your email address, has completed registration at YOURWEBSITE.com. You can complete registration by clicking the following link:rhttp://www.YOURWEBSITE.com/verify.php?$activationKeyrrIf this is an error, ignore this email and you will be removed from our mailing list.rrRegards, YOURWEBSITE.com Team";

$headers = 'From: noreply@ YOURWEBSITE.com' . "rn" .

    'Reply-To: noreply@ YOURWEBSITE.com' . "rn" .

    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

} else {

##User isn't registering, check verify code and change activation code to null, status to activated on success

$queryString = $_SERVER['QUERY_STRING'];

$query = "SELECT * FROM users"; 

$result = mysql_query($query) or die(mysql_error());

  while($row = mysql_fetch_array($result)){

    if ($queryString == $row["activationkey"]){

       echo "Congratulations!" . $row["username"] . " is now the proud new owner of an YOURWEBSITE.com account.";

       $sql="UPDATE users SET activationkey = '', status='activated' WHERE (id = $row[id])";

       if (!mysql_query($sql))

  {

        die('Error: ' . mysql_error());

  }

    }

  }

}

Verification Key Conclusion

So where should you take it from here? Obviously we haven’t included any error checking for input data. What if the user misspelled his or her password? We should probably put another password field in, and check to see if the passwords match. Additionally, we should mask the content in the password field to ensure security.

We might also add a CAPTCHA to prevent the mail server from getting abused by spam bots- something your host would probably appreciate. We could also simplify matters by using functions and cleaning up code.

There are many ways to improve- but be sure to check out our scripts and tutorials section for more information, because we’ve covered such topics like this in the past.

Comments
  1. Johnny
    April 15, 2009

    Wonderful tutorial! I just have one question is there a way to set a time limit for activating an account so that if they do not activate the account in so many days that it will automatically delete the account from the database to keep it nice and clean from people who never activate their accounts?

    Leave a reply
  2. Brian
    May 3, 2009

    What I have done is create a page that lists all accounts that have not been activated. You can then select to either activate them if you are the admin, or you can delete them as well. You need to have a switch to decipher between activated and non-activated. Overall it works extremely well and fast too.

    Leave a reply
  3. Apulis
    May 12, 2009

    Thank you man! Now waiting user login tutorial, how to accept approved users and ignore those who want to join without verification mail. And maybe you have something with imagre verification to prevent from computer submitting.

    Leave a reply
  4. rajesh
    May 14, 2009

    this is wonderful code for validation of email. i was searching last 2 hours and ultimately i found this. thnx buddy!.

    Leave a reply
  5. Vinayak
    May 14, 2009

    A nice tutorial…I like it. while implementing i changed steps little bit.Firstly, I take Email of user and send him or her a mail including activation key. if he or she verifies email provided then only i provide a page for registration.

    Leave a reply
  6. Alven
    May 18, 2009

    Nice script but when I tried it I found a problem after one record I received error duplicate entry key 4 so I think the problem is here
    activation wont work unless you have only one user because of this line
    $query = “SELECT * FROM users”;
    so do we need a WHERE clause?? may I ask you for a help??
    Thanks in advance.

    Leave a reply
  7. amit panchal
    May 21, 2009

    A nice tutorial…I like it. while implementing i changed steps little bit.i was searching last 2 hours and ultimately i found this. thnx

    Leave a reply
  8. SleepingTroll
    June 27, 2009

    Just include a timestamp in the database and test for status v. timestamp.

    Leave a reply
  9. opvaiop
    July 11, 2009

    I wish to do that but i don’t know how … will you be so kind to point me to some direction

    Leave a reply
  10. dinesh
    July 17, 2009

    great man,nice to see this

    Leave a reply
  11. adam
    July 25, 2009

    thanks..this code is perfect, i was looking for this since last year..thanks buddy..this really helps..

    Leave a reply
  12. laxika
    July 28, 2009

    Awesome! Ty for this! :)

    Leave a reply
  13. qwerty
    August 4, 2009

    What happened?? I didn’t received the activation code when i tried this…

    Leave a reply
  14. harris
    August 4, 2009

    this is wonder full,thanks for your valid code

    Leave a reply
  15. Rahul
    August 27, 2009

    this is awesome script. I mean i have been searching this script from last 2 hours and amazed to see the way its explained here.

    thanks a lot.

    Leave a reply
  16. Rahul
    August 27, 2009

    I am actually newbee to php to just learning things; got a small query in the code above:
    say i am making a forum website and i want user’s email id to be authenticated before activation of account, in that case what is the significance of:

    $headers = ‘From: noreply@ YOURWEBSITE.com’ . “rn” .

    ‘Reply-To: noreply@ YOURWEBSITE.com’ . “rn” .

    ‘X-Mailer: PHP/’ . phpversion();

    whose email id (noreply@ YOURWEBSITE.com) is this?

    also what is the use of header info??

    thanks in advance!!

    Leave a reply
  17. Kan
    September 1, 2009

    In response to Rahul question(s), I have difficulties understanding what you really mean.
    What do you really want to know: how to authenticate a user email address before activating his account OR you want to know the significance or the arguments passed to the header function OR maybe both . . .

    Leave a reply
  18. rusho
    September 3, 2009

    I dont receive any mail in the account for the activation….does anyone face the same problem?? what should i do??? I’m using mac osx

    Leave a reply
  19. St
    September 5, 2009

    Just wondering, why not use ‘WHERE’ to find the user with given activation link? Thanks for the whole tutorial though, its very helpful.

    Leave a reply
  20. sandeepj
    September 9, 2009

    Hi… thanks for the whole tutorial, it’s work fine for me. But only the question i want to ask it’s sending the mail to the smtp host name which i had written in php.ini. If I entered any other mail ids like yourname@gmail.com or any other it is showing following error.

    Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for spjahagirdar@rediffmail.com in C:wampwwwemailverify.php on line 39

    Leave a reply
  21. wycbux
    September 10, 2009

    i dont receive any mail neither… can anyone tell me what i’m doin wrong?
    thanks

    Leave a reply
  22. manish
    September 14, 2009

    this one is nice but may i knw somthing regarding the private content or profile how we can authenticate the client so that he or she can see his/her private content plz help me i am new to this php

    Leave a reply
  23. Noobeenoob
    October 1, 2009

    Okay, I have this implemented. Thanks for the info. Now what I wish to do is create the login page requesting email (will be used as username) and password to check against database and forward to content page. How do I do this?

    Leave a reply
  24. Ben
    October 6, 2009

    I had a big problem which meant two users couldn’t activate their account. Anyway this was due to blanking the activationkey. The way I fixed it was to remove activationkey = ” so it keeps the key in the database and just changes the status to “activated”. Otherwise it would say “Duplicate key 4 error”

    Leave a reply
  25. naresh
    October 10, 2009

    I used ur verify.php program im getting error “Undefined index: form_submitted in C:wampwwwverifyverify.php on line 4″, any one can solve my problem

    Leave a reply
  26. Jorge F.
    October 14, 2009

    Very nice tutorial. I’ve integrated your email activation script into my own register script. It all works very well!

    Leave a reply
  27. IamJim
    November 9, 2009

    I find myself wasting my time, as the SYNTAX is off many times: mysql_connect(“localhost”, “DATABASE”, “PASSWORD”) or die(mysql_error());

    Sometimes “DATABASE” is DATABASE

    No QUOTEs

    Why prints errors? Or code that does not work?

    Leave a reply
  28. charan315
    November 18, 2009

    i want registration and login code for webmail could any one help

    Leave a reply
  29. Sagar Gawas
    November 22, 2009

    That is very simple to use and Nicely written script. Very well done. If any one having problems using this script, I wonder if Their php concept are clear ;) Just kidding. With basic knowledge of mysql and php (mail, querystring), This is very simple to use script.

    Leave a reply
  30. Sagar Gawas
    November 22, 2009

    Very rare case of duplication key i think, plz explain so can help out…

    Leave a reply
  31. Glenn M
    November 30, 2009

    Thanks for a really nice tutorial!

    As a newbie, I am still trying to get a grip on how to secure my user data.

    When the connection to ”users” is established in this tutorial, a hard coded password is being used. I assume that I must create a separate database for my ”inventory”, that is protected with the newly created user name and password.

    I am concerned about using the hard coded password. Doesn’t this compromise the whole server?

    Thanks, Glenn

    Leave a reply
  32. soujanya
    December 3, 2009

    Its really wonderful.Im very thankful to you.Its such a nice tutorial that as a beginner this is my 1st day’s work with PHP is able to understand the code.

    Leave a reply
  33. Mohammad Zeeshan
    December 8, 2009

    Good i learn your website very easy examples and my learning process continue
    Thank You,

    Leave a reply
  34. babu
    December 14, 2009

    thank you for providing the details. it is very useful for me.
    regards
    babu.p
    srisoftwarez

    Leave a reply
  35. smRonju
    December 14, 2009

    Thanks buddy I have been looking for it.

    Leave a reply
  36. thornhillguy
    December 22, 2009

    I am looking for the same thing, any luck?

    Leave a reply
  37. neeraj pancholi
    December 28, 2009

    I am looking for the same thing, any luck?
    Good i learn your website very easy examples and my learning process continue
    Thank You,

    Leave a reply
  38. siyar
    January 11, 2010

    hi..
    i use this code but there is a problem ..
    when im clicking the activition link which is sent in registration time, then link opens but account doesnt activate
    ==> anyone help me ?

    Leave a reply
  39. Jessica
    January 14, 2010

    I got this one implemented just perfectly as what was described and expected. All of my users are activated!!! … I am struggling with activating only the a user with valid username, password and activation code in the database!

    Please help!

    Leave a reply
  40. Yogesh Powar
    January 18, 2010

    Great work!

    Thanks.

    Leave a reply
  41. dottomm
    January 25, 2010

    Thank you. This is a great tutorial.

    Leave a reply
  42. Manjunath Bhat
    February 15, 2010

    Hi,

    It was really a very good tutorail. I have implemented it.

    But i am facing a small problem. The records are being inserted in database but i am not getting any email. can any1 help me out. Please

    Leave a reply
  43. Nhoel
    February 18, 2010

    Sir your tutorial work for me but my email did not received verification and there is a error:
    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 D:xampphtdocstryverification.php on line 50
    Welcome!

    pls help!

    Leave a reply
  44. STACK_D
    February 18, 2010

    Thanks.Grate

    Leave a reply
  45. Mike
    February 22, 2010

    Works, but only once per user. Strictly for registration. I’m looking to verify email addresses prior to posting a classified, so this is not exactly what I’m looking for, but still very useful none the less- TY

    Leave a reply
  46. Paul
    February 28, 2010

    This is a very good tutorial. But 1 problem I am facing is that the activation key that is sending with the URL in the email is not the same as the 1 in the database so activation is not working when clicking the link.

    Activation is working when I enter the activation key from the database to the URL.

    Can please someone let me know how to fix it?

    Leave a reply
  47. sudeep
    March 1, 2010

    works very well easy to understand and modify very good thanks again !!

    Leave a reply
  48. STACK_D
    March 2, 2010

    Nhoel ,Nhoel, Nhoel

    That is not a problem in this code.
    we cant send an Email from at the local host.
    so u have to host that one.

    Leave a reply
  49. tsholo
    March 7, 2010

    How do i set or activate my email

    Leave a reply
  50. ali akbar
    March 20, 2010

    It’s amazing , i hope you keep your teaching
    thank you very much

    Leave a reply
  51. jhun
    March 22, 2010

    It was Good for now. but the thing here is i cant use my email anymore for
    debugging purposes, how can i use that again? Ty BRO!

    Leave a reply
  52. jhun
    March 23, 2010

    i got also a problem “duplicate key 4″ how do i fix this coz u can only activate one user only the rest will just stay ‘verify’ in the database… is it the query the problem?

    Leave a reply
  53. jbinspiration
    March 28, 2010

    Thank you very much your tutorial is so simple and straight forward. you are the man.I am going to use it for one my registration website. Thank you once again.

    Leave a reply
  54. Lucy Smith
    March 30, 2010

    What I am really after is for an email with the user’s name and email address to be sent to the person that I am creating the website for after they register as he wants to see who is registering, it’s only a small Satellite business on the island of Ibiza. If anyone could help me with that, please email me at casperibz@gmail.com xxx

    Leave a reply
  55. Brian B
    March 30, 2010

    I didn’t like the whole “verify” / “activated”, which works for some people but for me I just use 0 for not activated and 1 for activated.

    You build your form and have it run to this page…

    //loginRegister.php
    //These are the posted variables from the form
    $Email = $_POST[‘email’];
    $Pass = $_POST[‘password’];

    //This will check the database to make sure that the email, password, and the
    //status are all setup properly
    $result = mysql_query(“SELECT * FROM USERS WHERE email=’$Email’ and password=’$Pass’ and status=1″);
    $count = mysql_num_rows($result);
    //This section is optional for pulling certain form variables you want stored in
    //your session…
    while($row = mysql_fetch_assoc($result))
    {
    $userName = $row[‘userName’];
    $uID = $row[‘uID’];
    }
    //This checks to see if there was a match which means everything the user typed
    //in was correct and matched everything in the database
    if($count==1){
    // Register session variables and redirect to logged in page
    session_register(“userName”);
    session_register(“ID”);
    session_register(“Email”);
    session_register(“Pass”);
    header(“location:”LOGINPAGE”);
    }
    else
    {
    echo “Wrong Username or Password”;
    }

    Leave a reply
  56. arjun
    April 2, 2010

    very good i like this…

    Leave a reply
  57. Ric
    April 6, 2010

    this worked great.. really easy to follow.. now i am going to trying to .htaccess and mysql_auth to make this a basic registration system for a site

    Leave a reply
  58. Thomas
    April 9, 2010

    The script works fine for the first user but during activating the second user, I am getting the duplication key 3 error? can you help? Thanks!

    Leave a reply
  59. Thomas
    April 9, 2010

    for my previous posting: I am getting this Error: Duplicate entry ” for key 3

    Leave a reply
  60. M
    April 21, 2010

    I was also getting the following error:

    Error: Duplicate entry ” for key 4

    Here is a workaround:

    Change this:
    $sql=”UPDATE users SET activationkey = ”, status=’activated’ WHERE (id = $row[id])”;

    To this:
    $sql=”UPDATE users SET activationkey = ‘Done-$row[id]’, status=’activated’ WHERE (id = $row[id])”;

    Instead of emptying-out activationkey field we can set it as Done-$row[id] – it works :)

    Great tutorial. Thank you!!!

    Leave a reply
  61. preshila
    April 22, 2010

    thanks 2 help me again…….

    Leave a reply
  62. Geoffrey
    April 28, 2010

    this was very nice tutorial worked out for me.

    Leave a reply
  63. Suvo
    May 17, 2010

    i got the following arror. I don’t have still website provider. How can I set mailserver in my personal pc? local host
    An email has been sent to loknath@mail.ru with an activation key. Please check your mail to complete registration.
    Warning: mail() [function.mail]: Failed to connect to mailserver at “” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in B:Databasexampphtdocs3C_ServiceAlliance.update2verify.php on line 41

    Leave a reply
  64. carla
    June 7, 2010

    This is an excellent tutorial.
    The only things that are under question mark for me are:
    r does not move to a new line in the email message (“Welcome to our website!rrYou,……). Any idea why?
    Also I am using the same login.php for registration, verification and login.
    I need to couple the behaviour like registration+ login or after the registration is done and the user goes to his/her email to do the verification my php should show some thing like “congrats you are verified now”+ login panel.
    Is it a good practice to add to the verification hyperlink something like:
    mysite.com/Login.php?activation=1&activationkey=”.$activationKey.”????

    Leave a reply
  65. raj
    June 15, 2010

    Excellent article, however I think you need to alter the table structure for “users” a little bit in order to let the entire script work properly. The table structure provided with the tutorial marks “activationkey” as unique, thus, when a second activation comes in place, mySQL throws an sql error pointing towards the attempt to update the table with “” for a second record.
    The possible work arounds are
    1. Drop the table, create the table again without activationkey being unique.
    2. Change the update statement for the users table to only update the column status (ie, leaving the activation key field untouched!)

    Other than this, there are hardly much explanations about the mail() function call. To send a mail to the party who is registering, one must have PEAR MAIL configured with PHP properly.

    Works best with APACHE webserver, PHP5

    regards

    Leave a reply
  66. Mus
    June 17, 2010

    Very good, but it’s still not working for me, i do not be able to receive any notification.

    Leave a reply
  67. Sil
    June 18, 2010

    It worked perfectly, but anyone can tell how to do the login form?
    Thanks.

    Leave a reply
  68. Jacob
    June 25, 2010

    That’s better to place the echo with congrats after the sql query…

    Leave a reply
  69. sergio
    July 11, 2010

    a very cool script and easy to embed in our web pages.

    but i have few questions?
    1- when i click the activation link in my email the link point to an inexistent page. Why???
    2- how can i add a captcha verification?
    3- how can i set up a required fields and email verification?

    sorry for the all question but i’m very dummy about php

    Leave a reply
  70. sergio
    July 11, 2010

    what does it mean Error: Duplicate entry ” for key 2?

    Leave a reply
  71. Bob
    July 17, 2010

    Need to set up login / regester on my site. How do i get this information? and easy to follow instructions to set up these two items?

    Leave a reply
  72. Bob
    July 17, 2010

    on your first register.php script. using a php program. how and were do you upload this page to? mysql in a folder called? and the Groundwork For The Verification Process were does this uplod to: this is my problem. i have many scrips in php. but i am using yahoo. i have already set up my SQL folder. what do i name each folder? i use yahoo upload and i have wsftp. my big problem is also a submit button how do i link that to work usinf yahoo site builder. Does each php script you have listed here is seperated and uploaded to MSQL in a different folder for each script? i can copy everthing in each box above but where does these items go into what folder? i need step by step on what folder and named each folder to?? Thnaks

    Leave a reply
  73. Bob
    July 17, 2010

    Last question: each box indecated above, I have noticed that their is no name to each section: what would you callin box (Activation Key) should this file be called ActivationKey.php if is does this upload to MSQL folder or root folder? and you talk about upload to the database. what database do i need and how do i do that?

    Leave a reply
  74. plutonic888
    July 20, 2010

    i noticed no one said anything about this error message:
    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()

    To fix that WAMP server you need a software, i recommend POSTCAST SERVER (there’s a free version) just google it and download. install it (you’ll get an error just click ignore). run it and follow these steps:

    1. go to settings
    2. change the host name to localhost
    3. click detect on dns server address and you’re set
    4. go to wamp server on your task bar(bottom left screen) and open php.ini
    5. scroll down [mail function] and change smtp = localhost and smtp_port = 25
    6. make sure the pastcast server is running before running your registration script
    7. the email will be sent to the postcast server instead of the error
    8. click send and your email will be delivered to your emails spam folder

    I hope this helps.
    Great tutorial by the way.
    Farouk Tahir

    Leave a reply
  75. abdulhafeez
    July 22, 2010

    very nice class sir
    good work

    Leave a reply
  76. pavithra
    July 23, 2010

    I m very much happy to see this script. i tried it. thanks

    Leave a reply
  77. fazalyazdan
    July 27, 2010

    i am very very happy to see this script because this is very easy and helpful . Thank your very much

    Leave a reply
  78. Agus Haryanto
    August 16, 2010

    Great Tutorial, Thanks

    Leave a reply
  79. jaspreet singh
    August 22, 2010

    Wonderfully explained.. very easy to understand and work out!

    Leave a reply
  80. syam
    August 28, 2010

    Some great code here. Used it to create a membership site. Great job.

    Leave a reply
  81. Subodh
    August 28, 2010

    This is very nice script… thanks!

    Leave a reply
  82. Deano
    September 30, 2010

    Great script. You clearly know your php. This has helped me so much with my registration.
    I just have one problem. When I click on the link in my email, I am redirected to an error page and the database is not updated to “activated”. I think it could be an error with the server as my database server is different to my website server. But I am unable to change the code for this error. Could anybody help? I would really appreciate any help…

    Leave a reply
  83. supernova
    October 6, 2010

    great and useful tutorial .thanks a lot

    Leave a reply
  84. jhun
    October 7, 2010

    this was nice! but i do have problem every time php nail() script sends it happens to be spam mail or junk. what will i consider? ty it help alot

    Leave a reply
  85. arifinez
    October 14, 2010

    great, it works!
    thank you!

    Leave a reply
  86. Sayforever
    October 16, 2010

    Nice article dude! I’m a newbie in PHP. How hard is creating an Administrator?

    Leave a reply
  87. ansel
    October 27, 2010

    @ alven
    Yeah, do it like this
    [code]
    $sqloutput = mysql_query(“SELECT user_name, user_pass FROM users where user_name=’$UserName'”);
    [/code]

    $UserName is the variable you are testing it against.

    Leave a reply
  88. rajyesh
    November 29, 2010

    The article is very nice due to its simplicities.Only I suggest to make a simple adding in the verify.php file like:

    < ?php print "Click the link to activate your registration completed <a href='verify.php?$activationkey' rel="nofollow">Activate</a>"; ?>

    This will help them who are unable to send their email through localhost and so they cannot get the total input of your valuable script.Note:if anybody try this ,be aware of the fact that in your mail form,don’t put any value in the email field while submitting.
    Hope it will be fruitful for the beginners!

    Leave a reply
  89. Elton
    December 16, 2010

    Very simple really.
    How can we encrypt the password?

    Leave a reply
  90. Jugi
    January 22, 2011

    i used this code and the data entries are working perfectly but the email code doesn’t work. I used my email address and i didn’t receive it

    Leave a reply
  91. Jamie
    February 1, 2011

    Thanks for this, great article and easy to follow. The only problem I’ve had is where we have:

    UNIQUE KEY `activationkey` (`activationkey`)

    Once we have at least one user in the table, when validating and setting the `activationkey` to ”, MySQL complains with a duplicate entry for the key value. So, I assume we allow nulls and set the `activationkey` to NULL on successful validation?

    Leave a reply
  92. Raghav Rajagopalan
    February 2, 2011

    Respected,
    I am thankful to the coder for providing such a good code!! I have a small point to say. Y dont you merge in all the code together and make a zip file so that people can download the code easily. Don mistake me for this!! Any way thanks!!

    Leave a reply
  93. Anthony LPG
    February 3, 2011

    Agree with Raghav Rajagopalan on his comment at February 2, 2011

    Leave a reply
  94. santosh
    February 8, 2011

    This is good script , I’m try as click on submit button data are send to database but not send to email . thanks

    Leave a reply
  95. Monde
    February 10, 2011

    Thank you for the code.
    I’m very new to PHP and i was looking working this code and wanted to ask.
    I’m having issues with this
    $queryString = $_SERVER[‘QUERY_STRING’];
    for ‘QUERY_STRING’ what will i need to put in here.

    Thanks,
    Monde

    Leave a reply
  96. Eis
    February 19, 2011

    Thanks a million for this excellent tutorial. I’ve tried it and it worked perfectly well. Once again, thank you very much, and greetings from Indonesia :)

    Leave a reply
  97. Ray
    March 11, 2011

    First, this is one of the clearest, easiest to use, best written tutorials I’ve ever seen on this subject. THANK YOU SO MUCH for taking the time!

    For people above having email problems (perhaps this is worth saying in the real tutorial part) there are many web hosts (especially shared hosting) where you have to create the real “from:” email in order for mail to send. This is an anti-spam measure, and also ensures that you’re not spoofing. So if you’ve got everything working except the emails never arrive, try making sure you’ve set up a valid email in your host that you use there in the mail() section. Maybe that will help. Obviously there are lots of other things that could be happening too. Good luck!

    Leave a reply
  98. Raul
    March 12, 2011

    Excellent code. with minor modifications it works perfectly. I adapt it for a flash site written in AS3.
    Many thanks.
    Ragards,
    Raul

    Leave a reply
  99. silur
    March 14, 2011

    Awesome tutorial with 1 problem…
    the “is-submitted” function not working…
    if i load the xy.php file the hidden input valua’ll be 1 whitout submitting the form :S

    Leave a reply
  100. vipin
    March 17, 2011

    how can i get the mail in my inbox?i didnt get yet…i am using a localhost zend server….

    Leave a reply
  101. t9b
    March 18, 2011

    Security?
    Never ever EVER store a password in your database without – at the very least – encrypting it. Even if you intended to cover this topic elsewhere you should have at least mentioned it in warning.

    Other than that a good “get you started” guide;-)

    Leave a reply
  102. Mohammad Raihan Mazumder
    March 22, 2011

    mail($usr_email, “ЯAIHANMAZUMDER™ Login Details”, $message,
    “From: ”ЯAIHANMAZUMDER™ Member Registration” rn” .
    “X-Mailer: PHP/” . phpversion());

    above this script only for ONE email.. But if I want to send multiple email, what script i have to put here… Please reply me ASAP.

    Leave a reply
  103. Kinkar Jyoti Boro
    March 26, 2011

    Need to set up login / regester on my site. How do i get this information? and easy to follow instructions to set up these two items?

    Leave a reply
  104. eswete
    April 7, 2011

    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:xampphtdocstestingverify.php on line 41

    how to overcome this kind of problem??? i try various method but i have never receive any emails…
    somehow i wonder how the email will be sent because we never specify the website/ admin email password…
    if u have any idea how to send email, pls kindly tell me…

    Leave a reply
  105. Jethro Bryann
    April 8, 2011

    This is a good tutorial …. but i only have question?? how to put a query handler…. that will check if the e-mail is empty or password empty… in short check for empty fields b4 they can register to database???

    Leave a reply
  106. Jebac
    April 17, 2011

    < ?php print "Click the link to activate your registration completed Activate“; ?>

    This will help them who are unable to send their email through localhost and so they cannot get the total input of your valuable script.Note:if anybody try this ,be aware of the fact that in your mail form,don’t put any value in the email field while submitting.
    Hope it will be fruitful for the beginners!

    Leave a reply
  107. saranya
    April 27, 2011

    To send mail by using php code what to be set in php.ini file.my ISP is reliance.so what would be the mail server and if i use that means is it necessary to have account in that?

    Leave a reply
  108. kevin williams
    May 14, 2011

    having problems activating my tag account it keeps on asking for verification code and to check email i checked did not find any message what do i do from here

    Leave a reply
  109. Jame
    May 28, 2011

    Hi, Thanks for this good tutorials. This code works great, but why the Yahoo Mail can not receieve the mail from this code. I’ve tested with Yahoo and Gmail, but it worked only with Gmail. What is the problem?

    Leave a reply
  110. Douglas
    July 26, 2011

    Thanx alot that was wonderfull. i have just 1 question. Do you mind putting the whole code right from the start together to achieve just one complete code.
    Thanx again

    Leave a reply
  111. Trinity
    July 28, 2011

    Great tutorial! Only problem I have is due to reCAPTCHA I had to create a separate verification page. Problem when you visit the separate verification page without an activation code it returns a list of every user that has activated. It also sends another email to each user that has activated. How can I prevent this? I really don’t want to expose a listing of activated users.

    Leave a reply
  112. Rob Tomorrow
    September 16, 2011

    This is a nice tutorial it helped me learn how to use an activation key, but there is a problem with it that had me pulling my hair out for two days.

    In the Table you have the activationkey set as a Unique Key, then when the registration is activated you have the activationkey set to an empty string.

    That causes a conflict with the database because two records cannot have the same empty string because then they wouldn’t be unique.

    It is why several people have had a problem with duplicate activationkeys, in my case the code just wouldn’t work after the first record.

    Leave a reply
  113. Rob Tomorrow
    September 16, 2011

    Oh, and I fixed it by just removing the Unique Key status from the activationkey field.

    Leave a reply
  114. Rob Tomorrow
    September 16, 2011

    I see that you deleted my comment where I pointed out a mistake in the tutorial.

    I’m not complaining, this tutorial helped me understand how to use a activation key, but if the mistake wasn’t there I wouldn’t of been pulling my hair out for two days. It would be better to correct the mistake than to just delete the comment so others don’t have the same headaches.

    Just don’t make the activationkey column a Unique Key then the code wouldn’t break after the first user completes registration.

    Leave a reply
  115. Sandip
    October 2, 2011

    It is a great tutorial i had fetching no confusion to run this script.
    Thanks a lot for sharing this article.

    Leave a reply
  116. ArnieX
    October 22, 2011

    This helped me as well but let me mention some details, if you’d like to optimize DB usage do not unnecessarily use WHILE loop it is not welcomed in this place see why… If your registration form is advanced with absolute validation = no errors just correct validation so no one can actually fill out incorrect values and duplicates then you can just use UPDATE datatable SET value=’value’ WHERE actID=”.$actID and my advice is to MD5 users email and than use such function to encode MD5 with some numberletter to number encryption to make it just number but UNIQUE then you don’t have tu keep dumping your database with WHILE loop and just simply update the one unique ID. And if your registration form doesn’t allow one email to be registered twice and more. You don’t have to worry about nothing. Good to mention as well is that this MAIL build-in functionality works with only safe-mode OFF, once your host turn on SM ON you’re stucked in deep hole with no registration capabality :) needed to use some third party extension with SMTP sender.

    Leave a reply
  117. deepak
    November 12, 2011

    you write like a shekshpear.

    Leave a reply
  118. Skittles
    November 15, 2011

    One thing: You could have sped up the query by setting it to search for the row where the stored activation key is equal to the one from the email, so you aren’t selecting everything from that table.

    Leave a reply
  119. baby
    December 23, 2011

    Pleas I need you to help me in php
    I need to simple regstration of student
    I use xampp for database I made database id(AUTO_INCREMENT) ,fn,ln,email,gender,AGE,Adress

    so I need php code please

    Leave a reply
  120. Dan
    December 30, 2011

    Any one figured out a fix for the error message when clicking on the activation link? I am thinking this is a server issue but not sure how to work around it.

    Thanks

    Leave a reply
  121. palmspringsasian
    January 10, 2012

    Hi:

    I need scripts to create a form or a page to enable users to access the home page of my Web site after looging in.

    Thank you very much for your help in advance.

    Leave a reply
  122. Sric
    February 10, 2012

    Thanks for this tutorial, it’s very easy to follow, especially for someone with no PHP experience! I will have to do some reading on making this system more secure and more optimized for my database.

    I have a concern regarding the verification php page. If a user is sent to the verification page from the registration form, fine, nothing goes wrong. He is sent the email with the activation key. It is also working fine when the user is linked from the email with his activation key in the URL. However my concern is that when a user goes directly to, eg, “MY-PAGE.com/verify.php” by typing it directly into the address bar, he does not recieve an error message but instead a list of every user in the mysql server is shown to him. I worry that this is a very obvious and dangerous flaw in the system.

    How could this be fixed? Thanks ;)

    Leave a reply
  123. Sric
    February 12, 2012

    Ah, nevermind. Ignore my previous question. I did not have a full understanding of the PHP session. :) Lots of learning to do!

    Leave a reply
  124. ashley
    February 24, 2012

    hi sir!
    everything is fine but i get this error..

    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:xampphtdocsmyfristwebsiteverify.php on line 42

    plz help me..

    Leave a reply
  125. rinkarto
    April 16, 2012

    To clean up all unactivated keys, you can set a cron job to delete all keys older than a month or so. quite simple.

    Leave a reply
  126. Tendai
    April 19, 2012

    Great tut, and truly great follow up comments. The code works great. However, there’s need for serious validation on the verify.php page.

    Leave a reply
  127. Callum
    September 15, 2012

    Notice: Use of undefined constant username – assumed ‘username’ in C:wampwwwTest WebsiteVerify.php on line 10

    Notice: Use of undefined constant password – assumed ‘password’ in C:wampwwwTest WebsiteVerify.php on line 11

    Notice: Use of undefined constant email – assumed ‘email’ in C:wampwwwTest WebsiteVerify.php on line 13

    line 9: $activationKey = mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand();
    line 10: $username = mysql_real_escape_string($_POST[username]);
    line 11:$password = mysql_real_escape_string($_POST[password]);

    line 13: $email = mysql_real_escape_string($_POST[email]);

    Leave a reply
  128. Irina
    October 6, 2012

    Hi, thanks for the tutorial! was very detailed and clean. as far as code goes a couple things:
    1. you don’t need a hidden form element to see submition. instead you can set a name attribute on your submit button and then on verify page just use
    if(isset($buttonName))
    2. as it has been pointed out by others the sql query is well.. it’s okay if you have a small table but if you have a big one looping through each record like that is bad. after all you’re only looking for 1 specific row. the way I see it you could do something like “select count(*) where email = $email” if count is more than 1 then you have duplicates. but really you should know this even before that. when the user is submitting the data there should be a query looking for that email in the db (since email is unique). if there is an entry you should redirect back to registration with preserved values and alert the user that such an email is being used. if there is none proceed to inserting into database and just “select activationKey from users where email = $email”.

    however as far as tutorial goes it’s great for people to start with and build things around it not just copy paste it, not change anything, and then come back and complain :) I mean it’s programming this will point anyone with a question in the right direction and let them build things around it and better it. thanks again!

    Leave a reply
  129. Irina
    October 6, 2012

    oh and one more thing
    if(isset($_POST[‘register’]))
    {
    MySQL escape strings, insert statement yadda yadda

    if (!mysql_query($sql)) {
    die(‘Error: ‘ . mysql_error());
    }

    else {
    $msgAlert = “An email has been sent to $email with an activation key. Please check your mail to complete registration.”;

    email stuff blablabla
    }
    } (end of outter if)

    else{
    $msgAlert = “An error has occurred. Please try registering again.”;
    }

    and then in the body of the document just something like

    that will give the user a clue about his registration whereabouts. you could add specific reasons of what went wrong too. but that’s just the basic idea.

    Leave a reply
  130. Samir
    June 11, 2013

    i like this script and when i used i got this error message :

    Notice: Undefined index: form_submitted in …..my file

    this error comes from the first line to check if from url or the submit form

    —> if ($_POST[‘form_submitted’] == ‘1’) {

    any help please ?

    Leave a reply
  131. Eliza
    August 16, 2013

    Thank you for the great code. This is the error message I am getting
    “An email has been sent to eliza_hp11@gmail.com with an activation key. Please check your mail to complete registration.
    Warning: mail() [function.mail]: SMTP server response: 530 SMTP authentication is required. in C:\xampplite\htdocs\registrationformhelen\verify.php on line 41″

    I am a beginner at PHP so not sure what to do. I would appreciate your help please

    This is line 41 mail($to, $subject, $message, $headers);

    ##Send activation Email

    $to = $_POST[email];

    $subject = ” YOURWEBSITE.com Registration”;

    $message = “Welcome to our website!rrYou, or someone using your email address, has completed registration at YOURWEBSITE.com. You can complete registration by clicking the following link:rhttp://www.YOURWEBSITE.com/verify.php?$activationKeyrrIf this is an error, ignore this email and you will be removed from our mailing list.rrRegards, YOURWEBSITE.com Team”;

    $headers = ‘From: noreply@ YOURWEBSITE.com’ . “rn” .

    ‘Reply-To: noreply@ YOURWEBSITE.com’ . “rn” .

    ‘X-Mailer: PHP/’ . phpversion();

    mail($to, $subject, $message, $headers);

    } else {

    ##User isn’t registering, check verify code and change activation code to null, status to activated on success

    $queryString = $_SERVER[‘QUERY_STRING’];

    $query = “SELECT * FROM users”;

    $result = mysql_query($query) or die(mysql_error());

    while($row = mysql_fetch_array($result)){

    if ($queryString == $row[“activationkey”]){

    echo “Congratulations!” . $row[“username”] . ” is now the proud new owner of an YOURWEBSITE.com account.”;

    $sql=”UPDATE users SET activationkey = ”, status=’activated’ WHERE (id = $row[id])”;

    if (!mysql_query($sql))

    {

    die(‘Error: ‘ . mysql_error());

    }

    }

    }

    }

    Leave a reply
Leave a Comment Below »
Your Name
Your Email Address
Your Comment