Building Browsergames: The Registration Page (PHP)

Have you ever wanted to build your own browsergame, but not known how to begin or where to start? Generally, the easiest place to start is your registration page. It’s the page that users will see first when they’re interested in playing your game, and it’s how they will create their accounts before they login and begin playing your game. This write-up will try to guide you through building a basic registration page. It will also show you how you can put some database design tips to use when you build your database.

To begin with, we’ll need the database. Open up whatever utility you are using to administrate your databases(I use PHPMyAdmin), and create the proper new database and login for your new browsergame project. Here’s some SQL to setup your basic users table:

CREATE TABLE users (
	id int NOT NULL AUTO_INCREMENT,
	username varchar(250),
	password varchar(50),
	PRIMARY KEY(id)
);

Once that’s done, we can get to writing our code.

To begin with, we’ll need our registration form. Let’s just create a basic one:

<form method='post' action='register.php'>
Username: <input type='text' name='username' /><br />
Password: <input type='password' name='password' /><br />
Confirm Password: <input type='password' name='confirm' /><br />
<input type='submit' value='Register!' />
</form>

So now we have our form. But we don’t actually have anything in place to handle what our form does.

First off, let’s add something to check and see that the values being passed in as a password and a password confirmation match up:

<?php
	if($_POST) {
		$password = $_POST['password'];
		$confirm = $_POST['confirm'];	
		if($password != $confirm) { ?>
<span style='color:red'>Error: Passwords do not match!</span>		
<?php	}
	}
?>
<form method='post' action='register.php'>

Now, what did we do there?

First off, we checked to see if PHP’s internal variable $_POST had anything inside of it. If it didn’t, then there hasn’t been any data sent to our script to process – trying to process empty data would be pointless.

Then, we store the password and the password confirmation sent to us. We compare them, and if they’re not equal we spit out an error message.

The next feature we are going to add is checking to see whether the username that the user wants is available. In order to do that, we’ll need to connect to the database we created earlier, and run a query on the users table.

<?php	} else {
			$dbhost = 'localhost';
			$dbuser = 'user';
			$dbpass = 'pass';
			$dbname = 'name';	
		}

The first thing we did was define our database connection values. These will vary based on your specific configuration. $dbhost will be where your database is hosted – changes are, ‘localhost’ will be fine. $dbuser is the username you connect to the database with, and $dbpass is the password that matches that username. Finally, $dbname is the name of the database we will be working with after we have connected.

Once we have all our configuration data set up, we can actually connect to the database:

$conn = mysql_connect($dbhost,$dbuser,$dbpass)
				or die ('Error connecting to mysql');
			mysql_select_db($dbname);
		}

These lines of code will connect to the database, and then select the specific database we need to work with. The or die part of the code tells PHP that, if there’s an error connecting, it should ‘die’ with that error message. If you’re getting that error message when you’re testing, changes are it’s because your settings from earlier are not correct.

Once we’ve successfully established a connection to our database, we can begin to run queries on it:

$query = sprintf("SELECT COUNT(id) FROM users WHERE UPPER(username) = UPPER('%s')",
				mysql_real_escape_string($_POST['username']));
		}

Here, we stored our new query into $query. We’re going to be counting how many users exist within the users table that have the username we want, when both the username we want and their username are switched to uppercase. This will allow us to limit users to one unique username, along with making sure that the username “Foo” and “foo” mean the same thing – so there’s less confusion. We used the sprintf() function to format our output, so that we could use mysql_real_escape_string() to escape the value of $_POST[‘username’] before we put it into our query. We escaped our value so that we could avoid SQL Injection exploits. You should always escape any data you are going to use in a database query.

Once we have our query prepared, it’s time to execute it and retrieve our results.

$result = mysql_query($query);
			list($count) = mysql_fetch_row($result);
			if($count >= 1) { ?>
<span style='color:red'>Error: that username is taken.</span>
<?php		}
What we’ve done here is we’ve executed our query, and then stored what it returned into $count. Then, we’re checking to see what the value that came back was. If it’s greater than or equal to 1, then a user already exists with that username – and we therefore display an error message telling the user that the username they want is taken.

But we still haven’t built the main part of the register page yet – the actual registering part! So now we will do that. Just underneath our handling for the username being taken, add this:

[php]<?php		} else {
				$query = sprintf("INSERT INTO users(username,password) VALUES ('%s','%s');",
					mysql_real_escape_string($_POST['username']),
					mysql_real_escape_string(md5($password)));
				mysql_query($query);
			?>
<span style='color:green'>Congratulations, you've registered successfully!</span>
<?php
			}

That code will create an INSERT query that we can run, which will insert our new user into the database. Once again, we use sprintf() and mysql_real_escape_string() to make sure that we don’t have any SQL Injection problems. Something new that you should notice is that in the case of $password, we also pass it through another function – md5(). By passing it through md5, we get back a hashed version of our password. This means that it has been encrypted one way, and cannot be decrypted – so we can safely store our user’s passwords in our database, and even if someone gets access to it they won’t be able to steal user’s passwords. You should never store a user’s password in plaintext – it’s just asking for trouble.

After we’ve created and then executed our query, we print out another helpful message to tell the user that they registered successfully. And that’s that! You now have a working registration script, written in PHP. Here’s the code in it’s entirety:

<?php
	if($_POST) {
		$password = $_POST['password'];
		$confirm = $_POST['confirm'];	
		if($password != $confirm) { ?>
<span style='color:red'>Error: Passwords do not match!</span>		
<?php	} else {
			$dbhost = 'localhost';
			$dbuser = 'user';
			$dbpass = 'pass';
			$dbname = 'name';
			$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 {
				$query = sprintf("INSERT INTO users(username,password) VALUES ('%s','%s');",
					mysql_real_escape_string($_POST['username']),
					mysql_real_escape_string(md5($password)));
				mysql_query($query);
			?>
<span style='color:green'>Congratulations, you registered successfully!</span>
<?php
			}	
		}
	}
?>
<form method='post' action='register.php'>Username: <input type='text' name='username' /><br />
Password: <input type='password' name='password' /><br />
Confirm Password: <input type='password' name='confirm' /><br />
<input type='submit' value='Register!' />
</form>

If you want to check it out in action, you can see it here.

Would you like to see this in a language other than PHP? Send me an e-mail at buildingbrowsergames@gmail.com and I’ll get to work at building it for you.