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.
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.
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):
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.
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 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!\r\rYou, 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?$activationKey\r\rIf this is an error, ignore this email and you will be removed from our mailing list.\r\rRegards,\ YOURWEBSITE.com Team"; $headers = 'From: noreply@ YOURWEBSITE.com' . "\r\n" . 'Reply-To: noreply@ YOURWEBSITE.com' . "\r\n" . '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.
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!
##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!\r\rYou, 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?$activationKey\r\rIf this is an error, ignore this email and you will be removed from our mailing list.\r\rRegards,\ YOURWEBSITE.com Team"; $headers = 'From: noreply@ YOURWEBSITE.com' . "\r\n" . 'Reply-To: noreply@ YOURWEBSITE.com' . "\r\n" . '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()); } } } }
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.
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?
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.
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.
this is wonderful code for validation of email. i was searching last 2 hours and ultimately i found this. thnx buddy!.
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.
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.
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
Just include a timestamp in the database and test for status v. timestamp.
I wish to do that but i don’t know how … will you be so kind to point me to some direction
great man,nice to see this
thanks..this code is perfect, i was looking for this since last year..thanks buddy..this really helps..
Awesome! Ty for this!
What happened?? I didn’t received the activation code when i tried this…
this is wonder full,thanks for your valid code
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.
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’ . “\r\n” .
‘Reply-To: noreply@ YOURWEBSITE.com’ . “\r\n” .
‘X-Mailer: PHP/’ . phpversion();
whose email id (noreply@ YOURWEBSITE.com) is this?
also what is the use of header info??
thanks in advance!!
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 . . .
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
Just wondering, why not use ‘WHERE’ to find the user with given activation link? Thanks for the whole tutorial though, its very helpful.
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:\wamp\www\email\verify.php on line 39
i dont receive any mail neither… can anyone tell me what i’m doin wrong? thanks
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
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?
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”
I used ur verify.php program im getting error “Undefined index: form_submitted in C:\wamp\www\verify\verify.php on line 4″, any one can solve my problem
Very nice tutorial. I’ve integrated your email activation script into my own register script. It all works very well!
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?
i want registration and login code for webmail could any one help
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.
Very rare case of duplication key i think, plz explain so can help out…
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
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.
Good i learn your website very easy examples and my learning process continue Thank You,
thank you for providing the details. it is very useful for me. regards babu.p srisoftwarez
Thanks buddy I have been looking for it.
I am looking for the same thing, any luck?
I am looking for the same thing, any luck? Good i learn your website very easy examples and my learning process continue Thank You,
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 ?
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!
Great work!
Thanks.
Thank you. This is a great tutorial.
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
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:\xampp\htdocs\try\verification.php on line 50 Welcome!
pls help!
Thanks.Grate
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
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?
works very well easy to understand and modify very good thanks again !!
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.
How do i set or activate my email
It’s amazing , i hope you keep your teaching thank you very much
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!
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?
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.
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
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”; }
very good i like this…
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
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!
for my previous posting: I am getting this Error: Duplicate entry ” for key 3
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!!!
thanks 2 help me again…….
this was very nice tutorial worked out for me.
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:\Database\xampp\htdocs\3C_ServiceAlliance.update2\verify.php on line 41
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!\r\rYou,……). 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.”????
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
Very good, but it’s still not working for me, i do not be able to receive any notification.
It worked perfectly, but anyone can tell how to do the login form? Thanks.
That’s better to place the echo with congrats after the sql query…
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
what does it mean Error: Duplicate entry ” for key 2?
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?
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
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?
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
very nice class sir good work
I m very much happy to see this script. i tried it. thanks
i am very very happy to see this script because this is very easy and helpful . Thank your very much
Great Tutorial, Thanks
Wonderfully explained.. very easy to understand and work out!
Some great code here. Used it to create a membership site. Great job.
This is very nice script… thanks!