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!
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…
great and useful tutorial .thanks a lot
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
great, it works! thank you!
Nice article dude! I’m a newbie in PHP. How hard is creating an Administrator?
@ 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.
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!
Very simple really. How can we encrypt the password?
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
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?
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!!
Agree with Raghav Rajagopalan on his comment at February 2, 2011
This is good script , I’m try as click on submit button data are send to database but not send to email . thanks
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
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
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!
Excellent code. with minor modifications it works perfectly. I adapt it for a flash site written in AS3. Many thanks. Ragards, Raul
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
how can i get the mail in my inbox?i didnt get yet…i am using a localhost zend server….
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;-)
mail($usr_email, “ЯAIHANMAZUMDER™ Login Details”, $message, “From: \”ЯAIHANMAZUMDER™ Member Registration\” \r\n” . “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.
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\testing\verify.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…
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???
< ?php print "Click the link to activate your registration completed Activate“; ?>
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?
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
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?
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
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.
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.
Oh, and I fixed it by just removing the Unique Key status from the activationkey field.
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.
It is a great tutorial i had fetching no confusion to run this script. Thanks a lot for sharing this article.
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.
you write like a shekshpear.
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.
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
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
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.
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
Ah, nevermind. Ignore my previous question. I did not have a full understanding of the PHP session. Lots of learning to do!
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:\xampp\htdocs\myfristwebsite\verify.php on line 42
plz help me..
To clean up all unactivated keys, you can set a cron job to delete all keys older than a month or so. quite simple.
Great tut, and truly great follow up comments. The code works great. However, there’s need for serious validation on the verify.php page.
Notice: Use of undefined constant username – assumed ‘username’ in C:\wamp\www\Test Website\Verify.php on line 10
Notice: Use of undefined constant password – assumed ‘password’ in C:\wamp\www\Test Website\Verify.php on line 11
Notice: Use of undefined constant email – assumed ‘email’ in C:\wamp\www\Test Website\Verify.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]);