Creating the registration system
Now that we have some tools to use in our authentication system, lets create a registration form and processing script so users can register to gain access to our content. This file will display the registration form, process the data and handle any errors we may encounter. Lets look at it chunk by chunk.
File: register.php
<?php
require_once('common.inc.php');
// check if form has been submitted
if (isset($_POST['submit'])){
$registerComplete = false;
// initialize containers
$errors = array();
$post = $_POST;
// sanitize results
foreach ($post as $k => $v){
$post[$k] = escape_data($v);
}
// check for blank fields
if (strlen($post['username']) == 0)
$errors['username'] = "Please enter a valid username";
if (strlen($post['email']) == 0)
$errors['email'] = "Please enter a valid email";
if (strlen($post['first_name']) == 0)
$errors['first_name'] = "Please enter your first name";
if (strlen($post['last_name']) == 0)
$errors['last_name'] = "Please enter your last name";
// make sure username and email doesn't already exist
if (usernameExists($post['username']))
$errors['username'] = "That username is already in use";
if (emailExists($post['email']))
$errors['email'] = "That email is already in use";
// Other code
So we start out by including our common.inc.php file to make sure we have access to the resources we will need. Then the first thing we do is check to see if the form has already been submitted so we can start handling the data. We then initialize some variables, the $registerComplete variable will be used as a switch to show the appropraite display when the registration is complete, the $errors array will be used to store information on any errors encountered during the process, and the $post array will contain the post data.
Next we sanitize the data with the escape_data() function in our config.php file. This should help to protect us from SQL injection attacks. After that we check for empty strings and ensure that the posted username and email dont already exist using functions we created earlier.
One point for improvement here is to include some sort of email validation to verify that the email address is in the correct format. You can use whatever method you feel comfortable with, I usually use Zend Frameworks Zend_Validate_EmailAddress. However in this working example, if someone enters an incorrectly structured email address, the worst thing that happens is that they have to re-register with a different username and a correct email.
File: register.php (cont.)
// if no errors were found, process the registration
if (!(count($errors) > 0)) {
//generate password
$post['password'] = randPassword();
// execute function to add user
if (addNewUser($post)) {
// execute function to send email
if(sendRegisterEmail($post)) {
$registerComplete = true;
} else {
// error sending email add entry for debugging
$errors['debug'][] = "Error Sending email in 'sendRegisterEmail()'";
}
} else {
// error adding user, add entry for debugging
$errors['debug'][] = "error adding new user in authUtils.php function 'addNewUser()'";
}
}
} else { // form not submitted
$registerComplete = false;
}
?>
// Other code
The next thing we did is check our $errors array to see if we have encountered any errors thus far. If the script has it will fall through to the end, where the $registerComplete flag will still be set false and the errors will be displayed in our HTML. If no errors are encountered at this point we go ahead with adding the user to the database. We start by generating a random password and putting it in our $post array. We then try to add the user to the database, if that is successful, we try sending them the confirmation email. If theses steps are successfull, we set the $registerComplete variable to true, otherwise we store some information in the $errors array under a key named debug that will output some info to the screen for us. Lets go ahead and finish this script out!
File: register.php(cont.)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Registration Form</title>
<style type="text/css">
.error {
color : #f00;
font-weight : bold;
}
</style>
</head>
<body>
<?php if ($registerComplete): ?>
<h3 style="text-align:center;color:red;">
Thank you for registering with <?php echo SITE_NAME; ?> Please check your email for your account verification email.
</h3>
<?php else: ?>
<h3 style="text-align:center;color:red;">Sign Up With <?php echo SITE_NAME; ?></h3>
<hr />
<?php // display debuging errors
if(@count($errors['debug']) > 0 && DEBUG):
echo '<div class="error">Debug Errors<br />';
foreach($errors['debug'] as $error) {
echo $error . '<br />';
}
echo '</div>';
endif;
?>
<fieldset>
<legend>Sign Up</legend>
<?php if(@count($errors) > 0): ?>
<div class="error">
An error occurred in the form below
</div>
<?php endif; ?>
Here we start out our HTML content. First thing in the body we use a conditional to check the value of the $registerComplete variable. If it is true, meaning the form has been successfully processed, we display a message to the user thanking them for their registration and informing them to check their email. If it is not true, either the form hasn't been submitted or their was a problem, so we display the form.
We check for the existance of debug errors in our errors array and display them accordingly. After starting the form we create a error headline to inform the user that there may be errors in the form. If you aren't familiar with it, I threw a little of PHP's alternative syntax in there for you to check out. This is actually nice to use when throwing PHP in the mix with HTML.
File: register.php(cont.)
<form action="register.php" method="post">
<div class="form_row">
<label for="username">Username:</label>
<input type="text" name="username" value="<?php if(isset($post['username'])){echo $post['username']; } ?>" />
<?php if(isset($errors['username'])){
echo '<div class="error">' . $errors['username'] . '</div>';
}?>
</div>
<div class="form_row">
<label for="email">Email:</label>
<input type="text" name="email" value="<?php if(isset($post['email'])){echo $post['email']; } ?>" />
<?php if(isset($errors['email'])){
echo '<div class="error">' . $errors['email'] . '</div>';
}?>
</div>
<div class="form_row">
<label for="first_name">First Name:</label>
<input type="text" name="first_name" value="<?php if(isset($post['first_name'])){echo $post['first_name']; } ?>" />
<?php if(isset($errors['first_name'])){
echo '<div class="error">' . $errors['first_name'] . '</div>';
}?>
</div>
<div class="form_row">
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" value="<?php if(isset($post['last_name'])){echo $post['last_name']; } ?>" />
<?php if(isset($errors['last_name'])){
echo '<div class="error">' . $errors['last_name'] . '</div>';
}?>
</div>
<div class="form_row">
<input type="submit" name="submit" value="Register">
</div>
<a href="reset.php">Lost Password</a>
</form>
</fieldset>
<?php endif; ?>
</body>
</html>
Closing out the script we build our form, we include some php code to display the users previously entered values as well as any errors that might have been encountered with their entries.
Thats all there is to registering users for your site. Now we need to move on to logging them in and restricting access to content!