In this tutorial you will learn how to create a fully featured registration script, users will be able to enter your site, visit the registration page, fill in the info, submit the form, receive an activation e-mail and be able to activate there accounts.

Alright, this tutorial won’t teach you anything about design, so the finalized script won’t look pretty at all, but it is very easy to implement into any design.

First, we are going to need to create a table in our database so that we can store all of our registration info. We are going to call this table, users since that’s what it will store!
username VARCHAR(30) NOT NULL,
password CHAR(40) NOT NULL,
email VARCHAR(70),
active CHAR(32),
That little SQL creates our table to store all of our user information in, now we need a way to connect to the database.

DEFINE ('DB_USER', 'database username');
DEFINE ('DB_PASSWORD', 'database password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'database name');

$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error());

@mysql_select_db (DB_NAME) OR die('Could not select the database: ' . mysql_error() );	

This is just a file that we can use to connect to our database with, now all we need to do is include it any file that we want to query the database from.

Now that we have our table and mysql connection file setup, we need to create the PHP file that allows the person to register.

Let’s start off by creating the form processing part of the file, it will be included in the same file as the form.

if (isset($_POST['submitted'])) {

	$errors = array();
        require_once ('mysql_connect.php');

This part is easy, all it does is start a new PHP section, then our first if() statement is saying IF our form is submitted, then continue. We also start a new variable, and assign an array to it. So that we can echo out our errors (if there are any) at the end. We also include our mysql_connect.php file, since we will be querying the database.

	if (eregi('^[[:alnum:]\.\'\-]{4,30}$', stripslashes(trim($_POST['username']))) ) {
		$user = mysql_real_escape_string($_POST['username']);
		$query = "SELECT username FROM users WHERE username = '$user'";
		$result = @mysql_query($query);
		$num = @mysql_num_rows($result);
		if ($num > 0) {
			$errors[] = '<font color="red">The username you have chosen has already been taken, please try again.</font>';
		} else {
			$username = mysql_real_escape_string($_POST['username']);
	} else {
		$errors[] = '<font color="red">Please provide a valid username between 4 and 30 characters.</font>';

This is where we check our first field, the username field. We use regular expressions to validate that the username is good. It must only contain numbers, letters, periods and it must be between 4 and 30 characters. If our regular expressions passes all the tests, we query the database and check if the username has been taken, if it has been taking we add an error to our $error array. If it is not taken then we it is assigned to the $username variable.

**UPDATE V1.1** – I have fixed the error that so many people are getting, I made a mistake, I have now added extra security to the script and it should be pretty much bug free.

	if (!eregi('^[a-zA-Z]+[a-zA-Z0-9_-]*@([a-zA-Z0-9]+){1}(\.[a-zA-Z0-9]+){1,2}', stripslashes(trim($_POST['email'])) )) {
		$errors[] = '<font color="red">Please provide a valid email address.</font>';
	} else {
		$email = mysql_real_escape_string($_POST['email']);

This little tid-bit of code just validates there e-mail address using another regular expression.

	if (!empty($_POST['password1'])) {
		if ($_POST['password1'] != $_POST['password2']) {
			$errors[] = '<font color="red">The 2 passwords you have entered do not match.</font>';
		} else {
			$password = $_POST['password1'];
	} else {
		$errors[] = '<font color="red">Please provide a password.</font>';

This is where we validate our password(s). First we check if they entered in the first password, then if it isn’t empty, we make sure that password 1 and password 2 are the exact same (password, and verify password). If they do not match each other, we add an error to our $errors array. If they do match each other, we continue.

	if (empty($errors)) {
                $a = md5(uniqid(rand(), true));
		$query = "INSERT INTO users (username, email, password, active) VALUES ('$username', '$email', SHA('$password'), '$a')";
		$result = @mysql_query($query);
		if (mysql_affected_rows() == 1) {

                        // Send the E-Mail
                        $body = "Thank you for registering at the User Registration site. To activate your account, please click on this link:\n\n";
		        $body .= "" . mysql_insert_id() . "&y=$a";
			mail($_POST['email'], 'Registration Confirmation', $body, 'From:');

                        // Show thank you message
			echo '<h3>Thank You!</h3>
			You have been registered, you have been sent an e-mail to the address you specified before. Please check your e-mails to activate your account.';
		} else {
			echo '<font color="red">You could not be registered, please contact us about the problem and we will fix it as soon as we can.</font>';

This is the part where we do our error checking, if our $errors variable is empty (no errors) then we continue on with the form. So we insert everything into our users table, run the query, then check if it worked using mysql_affected_rows() == 1. If our query only affected 1 row (only inserted 1 user, no more and no less.) then our query worked, you are shown a message and the e-mail is sent to the user.

**UPDATE V1.2** – The query has been fixed, and everything has been personally tested and works now. If there is still more bugs please tell me.

If it didn’t work, (the query didn’t work) you are shown an error message.

	} else {
		echo '<h3>Error!</h3>
		The following error(s) occured:<br />';
		foreach ($errors as $msg) {
			echo " - <font color=\"red\">$msg</font><br />\n";

This is the finishing of the PHP section of our registration script, this is always where we check for errors. If the $errors array was not empty then the user is shown an error message and we use a foreach loop to display all of our errors and echo them out to the user. Then we end our PHP section.

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
	<p><input type="text" name="username" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>" size="30" maxlength="30" /> <small>Username</small></p>
	<p><input type="password" name="password1" size="30" maxlength="40" /> <small>Password</small></p>
	<p><input type="password" name="password2" size="30" maxlength="40" /> <small>Confirm Password</small></p>
	<p><input type="text" name="email" size="30" maxlength="30" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>" /> <small>Email Address</small></p>
	<p><input type="submit" name="submit" value="Register" /></p>
	<input type="hidden" name="submitted" value="TRUE" />

So I lied, there is still a little tiny bit of PHP but very simple stuff. Here we just create our form, with the corresponding names as in our PHP script. Make sure you name your the hidden input as submitted, this is how our PHP script knows that the form is submitted.

That is it for our registration part of our script, now we just have to do the activation part, this is a simple little script.

if (isset($_GET['x'])) {
	$x = (int) $_GET['x'];
} else {
	$x = 0;
if (isset($_GET['y'])) {
	$y = $_GET['y'];
} else {
	$y = 0;

if ( ($x > 0) && (strlen($y) == 32)) {

	require_once ('mysql_connect.php');
	$query = "UPDATE users SET active=NULL WHERE (user_id=$x AND active='" . $y . "') LIMIT 1";		
	$result = mysql_query($query);
	if (mysql_affected_rows() == 1) {
		echo "<h3>Your account is now active. You may now log in.</h3>";
	} else {
		echo '<p><font color="red" size="+1">Your account could not be activated. Please re-check the link or contact the system administrator.</font></p>'; 


} else {

	echo '<b>Activation link not valid!</b>';


This is just a simple little script, we start off by checking the x and y values in the URL to check if they are valid (or if someone is messing with us), we inclue our mysql_connect.php file into our script, since we will be using the database to query the right user. A user is considered active when the active field for there name is NULL (empty), so if the x and y values are right and everything works, we then set the active field to NULL. If only 1 account was affected, we echo out a success message and everything is done! If not, then the appropriate error message is echoed and the script stops.

** UPDATE V1.3** – Ok, the last of the escape_data() function bug has been removed (I really hope so) – and everything SHOULD work perfect. I know I’ve said that in previous versions, but I really mean it this time :)

If you want to use a login script with this registration script, make sure you check whether or not a user is active or not using a very simple query that selects the active field for the user, and then use an if statement to check whether it is NULL or not.

I hope you have been able to learn something from this script, please send us a comment using our contact form if you have any comments or questions!

**VERSION 1.3** April 16th, 2007- – The last of the escape_data() error has been fixed, (I hope) and everyone can continue on with there lives!
**VERSION 1.2** April 12th, 2007- – The insert query bug is fixed – everything should work perfect.
**VERSION 1.1** April 9th, 2007- – escape_data() function bug is fixed.