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

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

This chapter is from the book

Registration

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 www.DMCInsights.com/ecom/, 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:

register.php

 1  <?php
 2  require ('./includes/config.inc.php');
 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. paypal.com">
    PayPal</a>.</p>
 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 form_functions.inc.php file. I did this just before the page-specific content:

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

The form itself looks like:

<form action="register.php" method="post" accept-charset="utf-8"
 style="padding-left:100px">
   <p><label for="first_name"><strong>First Name</strong></label>
    <br /><?php create_form_input('first_name', 'text', $reg_errors); ?>
    </p>
   <p><label for="last_name"><strong>Last Name</strong></label>
    <br /><?php create_form_input('last_name', 'text', $reg_errors); ?>
    </p>
   <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.
    </small></p>
   <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" />
</form>

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 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, 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
             password!';
        }
    } 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
         username='$u'";
        $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.
         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.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.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020