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

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

Security Techniques

This chapter is from the book

Validating Form Data

Handling form data is still far and away the most common use of PHP (in this author's humble opinion, anyway). The security concern lies in the fact that the PHP page handling the form will do something with the information the user enters: store it in a database, pass it along to another page, or use it in an email. If the information the user enters is tainted, you could have a major problem on your hands. As a rule, do not trust the user! Mistakes can happen, either on purpose or by accident, that could reveal flaws in your code, cause the loss of data, or bring your entire system to a crashing halt.

Some good validation techniques are:

  • Use the checkdate() function to confirm that a given date is valid.
  • Typecast numbers.
  • Use regular expressions to check email addresses, URLs, and other items with definable patterns (see the sidebar).

As with the basic security techniques already reviewed, the hope is that as a somewhat-experienced PHP programmer, you already know most of these things. To be certain, this next example will present a sample registration form (Figure 4.1), taking various types of information, which will then be precisely validated. In doing so, I'll make use of a couple of Character Type functions, added to PHP in version 4.3. Listed in Table 4.1, these functions test a given value against certain constraints for the current locale (established by the setlocale() function).

Figure 4.1

Figure 4.1 When users first come to the registration page, this is the form they will see.

Table 4.1. The Character Type functions provide validation specific to the given environment (i.e., the locale setting).

Character Type Functions


Checks If Value Contains


Letters and numbers


Letters only


Control characters




Printable characters, except spaces


Lowercase letters


Printable characters




White space characters


Uppercase characters


Hexadecimal numbers

To validate a form

  1. Begin a new PHP script in your text editor or IDE, starting with the HTML (Script 4.1).
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    <html xmlns="" xml:lang="en" lang="en">
         <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
         <title>Registration Form</title>
    <?php # Script 4.1 - register.php

    Script 4.1. This page both displays a registration form and processes it. The script validates the submitted data using various functions, and then reports any errors.

    1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    2           "">
    3    <html xmlns="" xml:lang="en" lang="en">
    4    <head>
    5        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    6        <title>Registration Form</title>
    7    </head>
    8    <body>
    9    <?php # Script 4.1 - register.php
    11   /*  This page creates a registration form
    12    *  which is then validated using various functions.
    13    */
    15   if (isset($_POST['submitted'])) { // Handle the form.
    17       // Store errors in an array:
    18       $errors = array();
    20       // Check for non-empty name:
    21       if (!isset($_POST['name']) OR empty($_POST['name'])) {
    22           $errors[] = 'name';
    23       }
    25       // Validate the email address using eregi():
    26       if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$',
         $_POST['email'])) {
    27           $errors[] = 'email address';
    28       }
    30       // Validate the password using ctype_alnum():
    31       if (!ctype_alnum($_POST['pass'])) {
    32           $errors[] = 'password';
    33       }
    35    // Validate the date of birth using check_date():
    36    if (isset($_POST['dob']) AND
    37    (strlen($_POST['dob']) >= 8) AND
    38    (strlen($_POST['dob']) <= 10) ) {
    40        // Break up the string:
    41        $dob = explode('/', $_POST['dob']);
    43        // Were three parts returned?
    44        if (count($dob) == 3) {
    46            // Is it a valid date?
    47            if (!checkdate((int) $dob[0], (int) $dob[1], (int) $dob[2])) {
    48                $errors[] = 'date of birth';
    49            }
    51        } else { // Invalid format.
    52            $errors[] = 'date of birth';
    53        }
    55    } else { // Empty or not the right length.
    56        $errors[] = 'date of birth';
    57    }
    59    // Validate the ICQ number using ctype_digit():
    60    if (!ctype_digit($_POST['icq'])) {
    61        $errors[] = 'ICQ number';
    62    }
    64    // Check for non-empty comments:
    65    if (!isset($_POST['comments']) OR empty($_POST['comments'])) {
    66        $errors[] = 'comments';
    67    }
    69    if (empty($errors)) { // Success!
    71        // Print a message and quit the script:
    72        echo '<p>You have successfully registered (but not really).</p></body></html>';
    73        exit();
    75    } else { // Report the errors.
    77        echo '<p>Problems exist with the following field(s):<ul>';
    79        foreach ($errors as $error) {
    80            echo "<li>$error</li>\n";
    81        }
    83            echo '</ul></p>';
    85        }
    87    } // End of $_POST['submitted'] IF.
    89    // Show the form.
    90    ?>
    91    <form method="post">
    92    <fieldset>
    93    <legend>Registration Form</legend>
    94    <p>Name: <input type="text" name="name" /></p>
    95    <p>Email Address: <input type="text" name="email" /></p>
    96    <p>Password: <input type="password" name="pass" /> (Letters and numbers only.)</p>
    97    <p>Date of Birth: <input type="text" name="dob" value="MM/DD/YYYY" /></p>
    98    <p>ICQ Number: <input type="text" name="icq" /></p>
    99    <p>Comments: <textarea name="comments" rows="5" cols="40"></textarea></p>
    101   <input type="hidden" name="submitted" value="true" />
    102   <input type="submit" name="submit" value="Submit" />
    103   </fieldset>
    104   </form>
    106   </body>
    107   </html>
  2. Create the section of the script that handles the submitted form.

    if (isset($_POST['submitted'])) {
         $errors = array();

    Your script should always handle the form before it could possibly redisplay it (on errors found). I like to use a hidden form input to check if a form was submitted. The hidden form input will always be passed to the page upon submission, unlike any other input (on Internet Explorer, if a user submits a button by pressing Enter, then the submit button won't be set).

    One way I like to validate forms is to use an array that stores the errors as they occur. By checking if this array is empty, the script can tell if all validation tests have been passed. If the array isn't empty, its values can be used to print the error messages.

  3. Check for a name.
    if (!isset($_POST['name']) OR empty($_POST['name'])) {
         $errors[] = 'name';
    A person's name is one of those things that you can use regular expressions on, but it may not be worthwhile. A valid name can contain letters, spaces, periods, hyphens, and apostrophes. Under most circumstances, just checking for a nonempty name is sufficient.
  4. Validate the submitted email address.
    if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', $_POST['email'])) {
         $errors[] = 'email address';
    There are any number of patterns you can use to validate an email address, depending on how strict or liberal you want to be. This one is commonly seen. Certainly some invalid email addresses could slip through this expression, but it does add a sufficient level of security. Feel free to use a different pattern if you have one to your liking. Keep in mind that a user could enter a valid e-mail address that does not actually exist. Only some sort of activation process (sending the user an email containing a link back to the Web site) can confirm a real address.
  5. Validate the submitted password.

    if (!ctype_alnum($_POST['pass'])) {
         $errors[] = 'password';

    The form indicates that the password must contain only letters and numbers. To validate such values, the function ctype_alnum() works perfectly.

    In a real registration form, I would also recommend confirming the password with a second password input, then making sure both values match. I'm skipping that step here for brevity's sake.

  6. Begin checking to see if the user entered a valid date of birth.

    if (isset($_POST['dob']) AND
    (strlen($_POST['dob']) >= 8) AND
    (strlen($_POST['dob']) <= 10) ) {
         $dob = explode('/', $_POST['dob']);
         if (count($dob) == 3) {

    There is really no way of knowing if the information users enter is in fact their birthday, but PHP's built-in checkdate() function can confirm whether or not that date existed. Since the form takes the date of birth as a simple string in the format MM/DD/YYYY, the script must first confirm that something was entered. I also check if the string's length is at least eight characters long (e.g., 1/1/1900) but no more than ten characters long (e.g., 12/31/2000).

    This string is then exploded on the slashes to theoretically retrieve the month, day, and year values. Next, a conditional checks that exactly three parts were created by the explosion.

  7. Check if the date of birth is a valid date.
    if (!checkdate((int) $dob[0], (int) $dob[1], (int) $dob[2])) {
         $errors[] = 'date of birth';
    The checkdate() function confirms that a date is valid. You might want to also check that a user didn't enter a date of birth that's in the future or the too-recent past. Each value is typecast as an integer as an extra precaution.
  8. Complete the date of birth conditionals.
        } else {
               $errors[] = 'date of birth';
    } else {
        $errors[] = 'date of birth';
    The first else applies if the submitted value cannot be exploded into three parts. The second else applies if the value isn't of the right length.
  9. Validate the ICQ number.
    if (!ctype_digit($_POST['icq'])) {
        $errors[] = 'ICQ number';
    The ICQ number can only contain digits, so it makes sense to use the ctype_digit() function.
  10. Check for some comments.
    if (!isset($_POST['comments']) OR empty($_POST['comments'])) {
        $errors[] = 'comments';
    Comments really cannot be run through a regular expression pattern because any valid pattern would allow just about anything. Instead, a check for some value is made.
  11. If there were no errors, report upon the success.
    if (empty($errors)) {
        echo '<p>You have successfully registered (but not really).</p></body></html>';
    If no errors occurred, then $errors would still be empty. The script could then register the user (probably in a database). Here it just prints a message and terminates the script (so that the form isn't redisplayed) instead (Figure 4.2).
    Figure 4.2

    Figure 4.2 If all of the data passed through the various checks, this message is displayed.

  12. Report the errors.
    } else {
        echo '<p>Problems exist with the following field(s):<ul>';
        foreach ($errors as $error) {
                echo "<li>$error</li>\n";
        echo '</ul></p>';
    If $errors isn't empty, it contains all of the fields that failed a validation test. These can be printed in a list (Figure 4.3).
    Figure 4.3

    Figure 4.3 A lot of mistakes were made in this registration attempt, each reported back to the user.

  13. Complete the main conditional and the PHP code.
    } // End of $_POST['submitted'] IF.
  14. Create the HTML form.
    <form method="post">
    <legend>Registration Form</legend>
    <p>Name: <input type="text" name="name" /></p>
    <p>Email Address: <input type="text" name="email" /></p>
    <p>Password: <input type="password" name="pass" /> (Letters and numbers only.)</p>
    <p>Date of Birth: <input type="text" name="dob" value="MM/DD/YYYY" /></p>
    <p>ICQ Number: <input type="text" name="icq" /></p>
    <p>Comments: <textarea name="comments" rows="5" cols="40"></textarea></p>
    <input type="hidden" name="submitted" value="true" />
    <input type="submit" name="submit" value="Submit" />
    There's not much to say about the form except to point out that it does indicate the proper format for the password and date of birth fields. If you are validating data to a specification, it's important that the end user be made aware of the requirements as well, prior to submitting the form.
  15. Complete the page.
  16. Save the file as register.php, place it in your Web directory, and test in your Web browser.

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.


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.


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.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

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.


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


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


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 and we will process the deletion of a user's account.


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:

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

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.


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