Building Browsergames: Implementing an e-mail confirmation system (PHP)

Even though you probably don’t need a user’s e-mail address, there are still some situations where you need to verify e-mail addresses. So today, I’ll walk you through building an e-mail verification system in PHP.

We’ll start off with our registration page from earlier, and build off of that. First off, we’ll add a column to our users table to track the user’s e-mail address(we’ll use this to confirm our user), along with another column to track whether they’ve confirmed their e-mail or not:

ALTER TABLE  `users` ADD  `email` TEXT NOT NULL;
ALTER TABLE `users` ADD `confirmed` tinyint(1) NOT NULL DEFAULT 0;

Then, we’ll add an input box for the user’s e-mail address:

33
34
E-mail Address: <input type='text' name='email' /><br />
<input type='submit' value='Register!' />

In order to send our confirmation e-mails, we’ll use PHP’s built-in mail() function. All we’re going to change in our code is what happens after a user registers – we’ll send them a quick little e-mail to say “hey, click here to confirm your e-mail address!”:

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
				$email = $_POST['email'];
				$query = sprintf("INSERT INTO users(username,password,email) VALUES ('%s','%s','%s');",
					mysql_real_escape_string($_POST['username']),
					mysql_real_escape_string(md5($password)),
					mysql_real_escape_string($email));
				mysql_query($query);
				$to = $email;
				$subject = 'browsergame e-mail address confirmation';
				$message = "
<p>Hey! Thanks for signing up for the browsergame. Click below to confirm your e-mail address.</p>
<p><a href='http://website.com/confirm.php?email=$email'>below</a></p>";
				$headers = 'From: webmaster@example.com' . "\r\n" .
							'Content-type: text/html; charset=iso-8859-1' . "\r\n";
				mail($to,$subject,$message,$headers);
			?>
<span style='color:green'>Congratulations, you've registered successfully! A confirmation e-mail has been sent to the address you entered.</span>

And if you run a quick test of your script, you should see the e-mail show up in the inbox of whatever e-mail you decided to test it with!

This is all well and good, but what about our actual confirm page? We’ll need one of those to actually mark a user as ‘confirmed’ after they click on the link in the e-mail we sent to them. So let’s create that page.

The confirm page is actually pretty easy. All it needs to do is take in an e-mail address, and then use that e-mail to update a specific user’s information within the database(you could modify it to work off of any unique attribute you wanted, really):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
	if($_GET) {
		$email = $_GET['email'];
		require_once('config.php');
		$conn = mysql_connect($dbhost,$dbuser,$dbpass)
			or die ('Error connecting to mysql');
		mysql_select_db($dbname);
		$query = sprintf("SELECT COUNT(id) FROM users WHERE email = '%s' AND confirmed=0",
			mysql_real_escape_string($email));
		$result = mysql_query($query);
		list($count) = mysql_fetch_row($result);
		if($count >= 1) {
			$query = sprintf("UPDATE users SET confirmed=1 WHERE email = '%s'",
				mysql_real_escape_string($email));
			mysql_query($query);
?>
<span style='color:green'>Congratulations, you've confirmed your e-mail address!</span>
<?php
		} else {
?>
<span style='color:red'>Oops! Either that user doesn't exist, or that e-mail address has already been confirmed.</span>
<?php
		}
	}
?>

There’s really not that much to this one – all it does is look for users that have that particular e-mail address, and haven’t already confirmed their e-mail address. There’s nothing new in this code that you haven’t seen before.

And that’s all there is to e-mail confirmation! It’s really a lot simpler than you think. Here’s the revised registration page code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
	if($_POST) {
		$password = $_POST['password'];
		$confirm = $_POST['confirm'];	
		if($password != $confirm) { ?>
<span style='color:red'>Error: Passwords do not match!</span>		
<?php		} else {
			require_once('config.php');	
			$conn = mysql_connect($dbhost,$dbuser,$dbpass)
				or die ('Error connecting to mysql');
			mysql_select_db($dbname);
			$query = sprintf("SELECT COUNT(id) FROM users WHERE UPPER(username) = UPPER('%s')",
				mysql_real_escape_string($_POST['username']));
			$result = mysql_query($query);
			list($count) = mysql_fetch_row($result);
			if($count >= 1) { ?>
<span style='color:red'>Error: that username is taken.</span>
<?php			} else {
				$email = $_POST['email'];
				$query = sprintf("INSERT INTO users(username,password,email) VALUES ('%s','%s','%s');",
					mysql_real_escape_string($_POST['username']),
					mysql_real_escape_string(md5($password)),
					mysql_real_escape_string($email));
				mysql_query($query);
				$to = $email;
				$subject = 'browsergame e-mail address confirmation';
				$message = "
<p>Hey! Thanks for signing up for the browsergame. Click below to confirm your e-mail address.</p>
<p><a href='http://website.com/confirm.php?email=$email'>below</a></p>";
				$headers = 'From: webmaster@example.com' . "\r\n" .
							'Content-type: text/html; charset=iso-8859-1' . "\r\n";
				mail($to,$subject,$message,$headers);
			?>
<span style='color:green'>Congratulations, you've registered successfully! A confirmation e-mail has been sent to the address you entered.</span>
<?php
			}	
		}
	}
?>
<form method='post' action='register-email.php'>Username: <input type='text' name='username' /><br />
Password: <input type='password' name='password' /><br />
Confirm Password: <input type='password' name='confirm' /><br />
E-mail Address: <input type='text' name='email' /><br />
<input type='submit' value='Register!' />
</form>

And here’s the confirmation page code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
	if($_GET) {
		$email = $_GET['email'];
		require_once('config.php');
		$conn = mysql_connect($dbhost,$dbuser,$dbpass)
			or die ('Error connecting to mysql');
		mysql_select_db($dbname);
		$query = sprintf("SELECT COUNT(id) FROM users WHERE email = '%s' AND confirmed=0",
			mysql_real_escape_string($email));
		$result = mysql_query($query);
		list($count) = mysql_fetch_row($result);
		if($count >= 1) {
			$query = sprintf("UPDATE users SET confirmed=1 WHERE email = '%s'",
				mysql_real_escape_string($email));
			mysql_query($query);
?>
<span style='color:green'>Congratulations, you've confirmed your e-mail address!</span>
<?php
		} else {
?>
<span style='color:red'>Oops! Either that user doesn't exist, or that e-mail address has already been confirmed.</span>
<?php
		}
	}
?>

If you want to see it in action, you can check it out at the sample e-mail registration page, where the code you see above is being run.

Wish there was more?

I'm considering writing an ebook - click here.

.

Luke is the primary editor of Building Browsergames, and has written a large portion of the articles that you read here. He generally has no idea what to say when asked to write about himself in the third person.

Friday, May 9th, 2008 buildingbrowsergames, code, php
  • Hi!
    http://browsergame.freeiz.c...
    What is the error?
    I don't found.
    Please help me!
    Thanks

  • Red

    I got it figured out thanks Luke. By the way your site is very organized, informative, and easy to understand. Thank you for making these tutorials available.

  • Red

    I test my register page and it seems to work but I do still get an error:

    Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/axyse1/public_html/axnet/register.php on line 25
    Congratulations, you've registered successfully! A confirmation e-mail has been sent to the address you entered.

    Hey! Thanks for signing up for the browsergame. Click below to confirm your e-mail address.

    What would be causing this?

  • I'm not sure - you'd have to show me lines 22-25 of your register.php.

  • BUnzaga

    I am also not getting the confirmation email for some reason. I'll try to simplify the message and see if it is a formatting mistake.

  • BUnzaga

    Ok so I guess it wouldn't let me send an email from a fake email address on my server. Once I went in and actually added an email address, the message was sent successfully.

  • sachit

    i could not fix the mail ,does not send mail . Can we tell why?
    I think all the configuration is right but .....

  • antcox

    Hey guys,

    I am trying to implement this system as part of your tutorial but I am having a couple of problems, perhaps stemming from the same error. When I test my registration page at this stage it attempts to load 'register-email.php' as a new page which does not exist, unless I have somehow missed that part. Also sometimes it will update the database with the registrants information but no email will be sent out. I understand this may have something to do with my php.ini which I do have access to but I do not understand what I should be looking for to remove the error.
    Thanks in advance for any help you can offer, also thanks for an amazing tutorial!
    Ant

  • Thanks guys for this awesome and intuitive sample of how to implement email confirmation system.

    I can now go ahead and personalise it to meet my need. Great resource :)

  • Pretty neat, but what is it usefull for?
    It certainly does not proove that the user is able to read email sent to the address she says she is.

    Once the user confirms one account (the real one) and learns the confirmation URL, will be able to "confirm" any email address she wishes. bill.gates@microsoft.com? Just enter http://website.com/confirm.... in browser - voila!

    The real confirmation is to use some secret data (the templated URL is not secret) sent to the given e-mail address.
    You meay for example add another text column 'confirmation_token' to the DB, put some random string in it and send http://website.com/confirm.... to the given address. Then use the given token to flag validated in DB row. This way the user has no way of guessing the confirmation token unless she really got the email.

  • Shade

    Hi!

    I added this "confirmation_token". Have a look at this: http://pastebin.com/fd19ea57

    Oh and btw... i dont get any email after registering. :( But the the account is generated in the Databse.
    This is my register.php:
    http://pastebin.com/f3b82f8bb

  • welon

    Hey Shade,
    i've got a question to this part:

    ...And change it to this

    $query = sprintf("INSERT INTO users(username,password,email) VALUES ('%s','%s','%s','%s');",
    mysql_real_escape_string($_POST['username']),
    mysql_real_escape_string(md5($password)),
    mysql_real_escape_string($email),
    mysql_real_escape_string($confcode));
    ...

    You INSERT INTO 3 columns, but you add 4 values. How does MySQL consider this??

  • BUnzaga

    Hey is there any reason not to do something like this:
    $token = sha1(microtime());
    ?>

    I ask because it would be pretty handy to just do that and send it as the token.

  • No reason at all not to do it that way - send away :)

  • If you're not getting an e-mail after registering, chances are your SMTP
    settings aren't configured properly in your php.ini. You'll probably need to
    talk to your webhost to see what they should be.

  • Shade

    I got it now...it was just a wrong variable. ;)
    But the "confirmation_token" is free of errors.

    Anyway, thanks for answering!

  • Tem

    Hey Shade, which variable was wrong? I've been trying to follow your code and I can't find the bug.

  • Hi Tomasz,
    You're definitely right about our e-mail system not being particularly
    secure - and using tokens would be a much better way to make it that way.
    However, it seems that everyone wants e-mail confirmations to work
    differently - which is why it's built the way it is. Modifying it from how
    it is now to working now to however you want it to instead should be simple
    enough.

  • Awesome, this is the first time i've used a script off the web that just worked. And it's neat and tidy, simple and not over complicated.

blog comments powered by Disqus

About

Building Browsergames is a blog about browsergames(also known as PBBG's). It's geared towards the beginner to intermediate developer who has an interest in building their own browsergame.

Sponsors

Got Something to Say?

Send an e-mail to luke@buildingbrowsergames.com, or get in touch through Twitter at http://twitter.com/bbrowsergames