Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Registration

The registration form needs to present fields for everything being stored in the database. Plus, it’s common to have users confirm their password, just to make sure they know what it is (since password inputs don’t display the entered text, it’s easy to unknowingly make a mistake). The same PHP script will display the form and handle its results. Therefore, if the registration form is incomplete, it can be shown again, with the existing values in place, along with detailed error messages (Figure 4.3).

The registration script I came up with, which you can download from www.LarryUllman.com, is about 160 lines total, including comments. Rather than walk you through the entire script in one long series of steps, let’s look at this script as its three distinct parts.

Creating the Basic Shell

Every PHP page in the site—every script that a user will access directly and that won’t be included by other PHP scripts—has the same basic structure. First, it includes the configuration file; then the MySQL connection script; and then the HTML header (likely setting the page title beforehand). Next comes the page-specific content, and finally, the footer is included. Here, then, is what you can start with for register.php:

<?php
require('./includes/config.inc.php');
require(MYSQL);
$page_title = 'Register';
include('./includes/header.html');
?>

<h1>Register</h1>
<p>Access to the site's content is available to registered users at a cost of $10.00 (US) per year. Use the form below to begin the registration process. <strong>Note: All fields are required.</strong> After completing this form, you'll be presented with the opportunity to securely pay for your yearly subscription via <a href="http://www.paypal.com">PayPal</a>.</p>

<?php include('./includes/footer.html'); ?>

For the registration page, it’s important that you give the customer a sense of the process. You may want to graphically indicate the steps involved using a progress bar (or progress meter), although the process of registering for this site has only two steps. Also indicate how all the data will be used (for example, explain that the user won’t be spammed), and maybe refer the user to whatever site policies exist (I’ve created a link to a policy file in the footer). Just do everything you can to reassure the user that it’s safe to proceed.

Creating the Form

The registration form contains six inputs: four text and two password (plus the submit button). I’ve already defined a function for creating these inputs, so the first thing the registration form needs to do is include the form_functions.inc.php file. Do this just before the page-specific content:

require_once('./includes/form_functions.inc.php');
?><h3>Register</h3>

As a complication, the form_functions.inc.php script may already have been included by the header file (to make the login form). To ensure that form_functions.inc.php is also available here, without seeing an error for possibly including it a second time, the require_once() function is the appropriate way to include that file before the registration form.

The form itself looks like this:

<form action="register.php" method="post" accept-charset="utf-8">
<?php
create_form_input('first_name', 'text', 'First Name', $reg_errors);
create_form_input('last_name', 'text', 'Last Name', $reg_errors);
create_form_input('username', 'text', 'Desired Username', $reg_errors);
echo '<span class="help-block">Only letters and numbers are allowed.</span>';
create_form_input('email', 'email', 'Email Address', $reg_errors);
create_form_input('pass1', 'password', 'Password', $reg_errors);
echo '<span class="help-block">Must be at least 6 characters long, with at least one lowercase letter, one uppercase letter, and one number.</span>';
create_form_input('pass2', 'password', 'Confirm Password', $reg_errors);
?>
<input type="submit" name="submit_button" value="Next &rarr;" id="submit_button" class="btn btn-default" />
</form>

You’ll see that with the aid of the create_form_input() function, all the code for creating each input and handling all the errors is extremely simple. As an example, for the first name input, the function is called indicating that the input should have name and id values of first_name, should be of text type, and should use First Name as the label. The fourth argument to the function is an array of errors named $reg_errors. In a few pages, this array will be added to the registration script so that it’s already defined prior to this point. The same function is called for all six inputs, changing the arguments accordingly.

For the username and passwords, the user is being presented with a clear indication of what’s expected of them. It drives me crazy when sites complain that I didn’t complete a form properly (such as by not using at least one number or capital letter in a password) when no such instructions were included.

Processing the Form

The bulk of the register.php script is the validation of the form and the insertion of the new record into the database. That part of the script is over one hundred lines of code, so I’ll walk through it more deliberately. Figure 4.4 shows a flowchart of how this entire page will be used and may help you understand what’s going on with the code. Note that all the code in the steps that follow gets placed after the MySQL connection script is included—because you’ll need access to the database—but before the form_functions.inc.php include and the page-specific content. Again, see the downloadable scripts if you’re confused about the order of things.

  1. Create an empty array for storing errors:

    $reg_errors = array();

    This array will be used to store any errors that occur during the validation process. Normally, I might include this line within the section that begins the validation process (see Step 2), but because the create_form_input() function calls are going to use $reg_errors the very first time the page is loaded, you need to create this empty array at this point.

  2. Check for a form submission:

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    The first time the user goes to register.php (that is, when the user loads the form), it will be a GET request. In that case, this conditional, and all the code to follow, won’t apply. When the user clicks submit, a POST request will be made of register.php, and this code will be executed.

  3. Check for a first name:

    if (preg_match ('/^[A-Z \'.-]{2,45}$/i', $_POST['first_name'])) {
       $fn = escape_data($_POST['first_name'], $dbc);
    } else {
       $reg_errors['first_name'] = 'Please enter your first name!';
    }

    Names are difficult to validate, so I’m using a regular expression that’s neither too strict nor too lenient. The pattern insists that the submitted value be between 2 and 45 characters long and only contain a combination of letters (case-insensitive), the space, a period, an apostrophe, and a hyphen. If the value passes this test, the escaped version of that value is assigned to the $fn variable. If the value doesn’t pass this test, a new element is added to the $reg_errors array. The element uses the same key as the form input so that the create_form_input() function can properly display the error.

    Alternatively, you could just check that this value isn’t empty, and then run it through strip_tags() to make sure it doesn’t contain anything it shouldn’t.

  4. Check for a last name:

    if (preg_match ('/^[A-Z \'.-]{2,45}$/i', $_POST['last_name'])) {
       $ln = escape_data($_POST['last_name'], $dbc);
    } else {
       $reg_errors['last_name'] = 'Please enter your last name!';
    }

    This is the same code as for the first name, but with a longer maximum length.

  5. Check for a username:

    if (preg_match ('/^[A-Z0-9]{2,45}$/i', $_POST['username'])) {
       $u = escape_data($_POST['username'], $dbc);
    } else {
       $reg_errors['username'] = 'Please enter a desired name using only letters and numbers!';
    }

    The username, per the instructions indicated in the form, is restricted to just letters and numbers. The username has to be between 2 and 45 characters long.

  6. Check for an email address:

    if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
       $e = escape_data($_POST['email'], $dbc);
    } else {
       $reg_errors['email'] = 'Please enter a valid email address!';
    }

    Unlike names, email addresses have to adhere to a fairly strict syntax. The simplest and most fail-safe way to validate an email address is to use PHP’s filter_var() function, part of the Filter extension added in PHP 5.2. Its first argument is the variable to be tested, and its second is a constant representing a validation model.

    If you’re not using a version of PHP that supports the Filter extension, you’ll need to use a regular expression instead (you can find good patterns online and in my books).

  7. Check for a password and match against the confirmed password:

    if (preg_match('/^(\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,}$/', $_POST['pass1']) ) {
       if ($_POST['pass1'] === $_POST['pass2']) {
          $p = $_POST['pass1'];
       } else {
          $reg_errors['pass2'] = 'Your password did not match the confirmed password!';
       }
    } else {
       $reg_errors['pass1'] = 'Please enter a valid password!';
    }

    OK, so, um, here’s a little magic for you. Good validation normally uses regular expressions, with which not everyone is entirely comfortable. And, admittedly, I often have to look up the proper syntax for patterns, but this one requires a high level of regular expression expertise. For the password to be relatively secure, it needs to contain at least one uppercase letter, one lowercase letter, and one number. In other words, it can’t just be a word out of the dictionary, all in one case. Creating a regular expression that confirms that these characters exist in the password, but in any position in the string, requires what’s called a zero-width positive lookahead assertion, represented by the ?=. The positive lookahead makes matches based on what follows a character. Rather than reading a page of explanation as to how this pattern works beyond that simple definition, you can test it for yourself to confirm that it does and research zero-width positive lookahead assertions online if you’re curious.

    Note that the password doesn’t need to be run through the escape_data() function. The password itself won’t be used in a query, but rather the hash of the password will be.

  8. If there are no errors, check the availability of the email address and username:

    if (empty($reg_errors)) {
       $q = "SELECT email, username FROM users WHERE email='$e' OR username='$u'";
       $r = mysqli_query($dbc, $q);
       $rows = mysqli_num_rows($r);
       if ($rows === 0) {

    If the $reg_errors array is still empty, no errors occurred (because even one error would add an element to this array, making it no longer empty). Next, a query looks for any existing record that has the submitted email address or username. In theory, this query could return up to two records (one for the email address and one for the username); if it returns no records, it’s safe to proceed.

  9. Add the user to the database:

    $q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires) VALUES ('$u', '$e', '"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln', ADDDATE(NOW(), INTERVAL 1 MONTH) )";
    $r = mysqli_query($dbc, $q);

    The query uses the submitted values to create a new record in the database. Note that for the password value, the password_hash() function is called. If you’re not using PHP 5.5 or later, you’ll need to install and include the password_compat library prior to this first line.

    The user’s type doesn’t need to be set because if no value is provided for an ENUM column, the first enumerated value—here, member—will be used.

    Until PayPal is integrated (see Chapter 6, “Using PayPal”), I’m setting the account expiration date to a month from now. Once PayPal has been integrated, the expiration will be set to yesterday. In that case, when PayPal returns an indication of successful payment, the user’s account will subsequently be set to expire in a year.

  10. If the query created one row, thank the new customer and send out an email:

    if (mysqli_affected_rows($dbc) === 1) {
       echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! You may now log in and access the site\'s content.</p></div>';
       $body = "Thank you for registering at <whatever site>. Blah. Blah. Blah.\n\n";
       mail($_POST['email'], 'Registration Confirmation', $body, 'From: admin@example.com');
       include('./includes/footer.html');
       exit();

    First, a Thanks! page is displayed (Figure 4.5). The next step would be to send the user off to PayPal, which will be added in Chapter 6. Also, an email can be sent to the user saying whatever you want, although you shouldn’t include the user’s password in that email. Finally, the footer is included and a call to exit() stops the page. This is necessary so that the registration form isn’t shown again, thereby confusing the user.

  11. If the query didn’t work, create an error:

    } else {
       trigger_error('You could not be registered due to a system error. We apologize for any inconvenience. We will correct the error ASAP.');
    }

    At this point, if the query didn’t create a new row, there was a database or query error. In that case, the trigger_error() function is used to generate an error that will be managed by the error handler in the config file. On a live, already tested site, this would likely occur only if the database server is down or overloaded.

  12. If the email address or username is unavailable, create errors:

    if ($rows === 2) {
       $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';
       $reg_errors['username'] = 'This username has already been registered. Please try another.';

    The else clause applies if the SELECT query returns any records. This means that the email address and/or the username have already been registered. If so, the next step is to determine which of the two values is the culprit.

    If two rows were returned, both have already been registered. The assumption would be that the same customer already registered (because her email address is in the system) and another customer already has that username (because it’s associated with a different email address). The error messages are added to the $reg_errors array, indexed at email and username, so that the errors can appear beside the appropriate form input when the form is redisplayed.

  13. Confirm which item has been registered:

    } else {
       $row = mysqli_fetch_array($r, MYSQLI_NUM);
       if( ($row[0] === $_POST['email']) && ($row[1] === $_POST['username'])) {
          $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';
          $reg_errors['username'] = 'This username has already been registered with this email address. If you have forgotten your password, use the link at left to have your password sent to you.';
       } elseif ($row[0] === $_POST['email']) {
          $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';
       } elseif ($row[1] === $_POST['username']) {
          $reg_errors['username'] = 'This username has already been registered. Please try another.';
       }
    } // End of $rows === 2 ELSE.

    If only one row was returned, the code needs to figure out if the username matched, the email address matched, or both matched in the same record. Three conditionals test for each possibility, with appropriate error messages assigned (Figures 4.6 and 4.7).

  14. Complete the conditionals:

          } // End of $rows === 0 IF.
       } // End of empty($reg_errors) IF.
    } // End of the main form submission conditional.
  15. Save and test the registration script.
  • + Share This
  • 🔖 Save To Your Account