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


Now that the helper functions have been defined, let's make the actual scripts that perform the account services, starting with registration. The registration form needs to present fields for everything being stored in the database. Plus, it's standard to have the user confirm their password, just to make sure they know what it is (as 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.7).

The registration script I came up with, which you can download from, 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 HTML header (likely setting the page title beforehand), and then the MySQL connection script. Next comes the page-specific content and, finally, the footer is included. Here then, is what you can start with for register.php:


 1  <?php
 2  require ('./includes/');
 3  $page_title = 'Register';
 4  include ('./includes/header.html');
 5  require (MYSQL);
 6  ?><h3>Register</h3>
 7  <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.">
 8  <?php
 9  include ('./includes/footer.html');
10  ?>

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 this particular process really only has two steps. Also indicate how all the data will be used (for example, explain that they won't be spammed), and maybe refer them 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). We've already defined a function for creating these inputs, so the first thing the registration form needs to do is include the file. I did this just before the page-specific content:

require ('./includes/');

The form itself looks like:

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

You'll see that with the aid of the create_form_input() function, all the code for creating each input plus 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 and should be of text type. The third 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. This same function is called for all six inputs, changing the arguments accordingly.

For the username and passwords, note that the user is being presented with a clear indication of what's expected of them. It drives me crazy when sites complain that I did not 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 100 lines of code, so I'll walk through it more deliberately. Figure 4.8 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 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, it will be a GET request, so 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,20}$/i', $_POST['first_name'])) {
        $fn = mysqli_real_escape_string ($dbc, $_POST['first_name']);
    } 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 20 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, then the escaped version of that value is assigned to the $fn variable. If the value does not pass this test, then 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.

  4. Check for a last name:

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

    This is pretty much 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,30}$/i', $_POST['username'])) {
        $u = mysqli_real_escape_string ($dbc, $_POST['username']);
    } else {
        $reg_errors['username'] = 'Please enter a desired name!';

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

  6. Check for an email address:

    if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $e = mysqli_real_escape_string ($dbc, $_POST['email']);
    } 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,20}$/', $_POST['pass1']) ) {
        if ($_POST['pass1'] == $_POST['pass2']) {
            $p = mysqli_real_escape_string ($dbc, $_POST['pass1']);
        } else {
            $reg_errors['pass2'] = 'Your password did not match the confirmed
    } else {
        $reg_errors['pass1'] = 'Please enter a valid password!';

    Okay, so, um, here's a little magic for you. Good validation normally uses regular expressions, with which not everyone is entirely comfortable. And, admittedly, even 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 upon 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 really curious.

  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
        $r = mysqli_query ($dbc, $q);
        $rows = mysqli_num_rows($r);
        if ($rows == 0) { // No problems!

    If the $reg_errors array is still empty, then 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 2 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', '"
     . create_password_hash($p) . "', '$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 get_password_hash() function is called. The user's type does not 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 in 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 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 '<h3>Thanks!</h3><p>Thank you for registering! You may now
         log in and access the site\'s content.</p>';
        $body = "Thank you for registering at <whatever site>. Blah. Blah.
        mail($_POST['email'], 'Registration Confirmation', $body, 'From:');
        include ('./includes/footer.html');

    First, a Thanks! page is displayed (Figure 4.9). The next step would be to send them off to PayPal, which we'll add in Chapter 6. Also, an email can be sent to the user saying whatever you want, although do not 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.');

    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 configuration 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:

    } else {
        if ($rows == 2) { // Both are taken.
            $reg_errors['email'] = 'This email address has already been
              registered. If you have forgotten your password, use the link at
              right 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. Now we need to determine which of the two values is the culprit. If two rows were returned, then both have already been registered. The assumption then is that the same customer already registered (because their 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 they'll appear beside the appropriate form input when the form is redisplayed.

  13. Confirm which item has been registered:
    } else { // One or both may be taken.
        $row = mysqli_fetch_array($r, MYSQLI_NUM);
        if( ($row[0] == $_POST['email']) && ($row[1] == $_POST
         ['username'])) { // Both match.
            $reg_errors['email'] = 'This email address has already been
             registered. If you have forgotten your password, use the link at
              right 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
              right to have your password sent to you.';
        } elseif ($row[0] == $_POST['email']) { // Email match.
            $reg_errors['email'] = 'This email address has already been
              registered. If you have forgotten your password, use the link at
              right to have your password sent to you.';
        } elseif ($row[1] == $_POST['username']) { // Username match.
            $reg_errors['username'] = 'This username has already been
              registered. Please try another.';
    } // End of $rows == 2 ELSE.

    If only one row was returned, then 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.10 and 4.11).

  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