Validation and Error Handling in PHP  Hot PDF Print E-mail
Tag it:
Delicious
Furl it!
Digg
NewsVine
Reddit
YahooMyWeb
Technorati
Articles Reviews PHP
Written by JOHN   
Tuesday, 17 April 2007
Article Index
Validation and Error Handling in PHP  Hot
Pattern Matching
Quantifiers
Anchors
Character classes
Executing pattern matches in PHP
Redisplaying a form
About the book and author

{mos_sb_discuss:37}

We've already discussed performing validation within our PHP code. In this chapter, we'll explore our options for validating form data before a form submission. We'll also discuss what to do when validation fails, and how to process other errors. We can check information on the client side in the user's browser using JavaScript. We can also check the data when it's submitted directly in PHP.


 
There's some information that can go out as part of a production error message that is not harmful for end users. For example, it's OK to say that you're having a problem connecting to your database. However, you don't want to reveal more information than is necessary in an error messages that may go out to end users.

For example, you don't want to disclose the IP address of your database and certainly not the username that was attempted when you tried to connect. Both of those could aid a potential attacker in breaking in when the database comes back online.

Validating User Input with JavaScript

On the client side, your best tool for validating data is JavaScript. JavaScript is different than PHP, because it's designed to execute in the user's browser instead of on the server. Because it executes in the client's computer, JavaScript is not allowed to access anything that could be a security risk, such as the local filesystem or network resources. JavaScript is primarily used in web pages. Although its name sounds like Java, it has no relationship to it.

Since this processing is built into most modern browsers, it's not difficult for end users to disable it. Therefore, even when you use JavaScript, always take precautions to handle the possibility of it not being present on the browser.

Some of the practical things you can do with JavaScript are checking fields and alerting the user to a problem before the data is submitted to the server. The validation can be as simple as checking for an empty field or more complex checks such as validating an email address.

Although JavaScript provides immediate feedback to a user if a field doesn't pass validation, it shouldn't be relied upon as the only validation method. Your PHP code should always perform the final validation.

JavaScript has many functions built in for validating fields. They range from the familiar length function to more complex and powerful regular expressions. We'll discuss regular expressions in more detail later. For now, all you need to know is that they provide a way of concisely describing what a string should look like. For example, an email address should have an at (@) sign with alphanumeric characters before and after it, such as This e-mail address is being protected from spam bots, you need JavaScript enabled to view it

There is one non-JavaScript tactic you can use to reduce client-side errors. You can set the MAXLENGTH attribute in your form's text fields. This prevents users from entering strings that are too large.

Let's go ahead and work with Example 15-1, which validates before submission.

<SCRIPT LANGUAGE="JavaScript1.2" SRC="source.js">
</SCRIPT>

<HTML>
<HEAD>
    <TITLE>Sample Form</TITLE>
</HEAD>

<SCRIPT LANGUAGE="JavaScript1.2">
    function check_valid(form) {
    var error = "";
    error += verify_username(form.username.value);
    error += verify_password(form.password.value);
    error += verify_phone(form.phone.value);
    error += verify_email(form.email.value);
    if (error != "") {
       alert(error);
       return false;
    }
return true;
}
</SCRIPT>

<BODY BGCOLOR="#FFFFFF">
    <FORM action="process.php" METHOD="post"
onSubmit="return check_valid(this)" id="test1" name="test1">
    <TABLE BORDER="0" WIDTH="100%" CELLSPACING="0" CELLPADDING="0">
        <TR>
            <TD WIDTH="30%" ALIGN="right">Username</TD>
            <TD WIDTH="70%">: <INPUT TYPE="text" NAME="username"></TD>
        </TR>
        <TR>
            <TD ALIGN="right">Password</TD>
            <TD>: <INPUT TYPE="password" NAME="password"></TD>
        </TR>
        <TR>
            <TD ALIGN="right">Phone</TD>
            <TD>: <INPUT TYPE="phone" NAME="phone"></TD>
        </TR>
        <TR>
            <TD ALIGN="right">Email</TD>
            <TD>: <INPUT TYPE="email" NAME="email"></TD>
        </TR>
        <TR>
            <TD> </TD>
            <TD><INPUT TYPE="SUBMIT" VALUE="Submit"></TD>
        </TR>
    </TABLE>
    </FORM>
</BODY>
</HTML>

Example 15-1 includes the JavaScript in Example 15-2. The SRC= tag within the SCRIPT element includes the script that makes the functions available within the HTML source file.

// verify username - 610 chars, uc, lc, and underscore only.
function verify_username (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a username.\n";
}
    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if ((strng.length < 6) || (strng.length > 10)) {
       error = "The username is the wrong length. It must be 6-10 characters.\n";
    }
    else if (illegalChars.test(strng)) {
    error = "The username contains illegal characters.\n";
    }
return error;
}

// verify password - between 68 chars, uppercase, lowercase, and numeral
function verify_password (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a password.\n";
}
    var illegalChars = /[\W_]/; // allow only letters and numbers
    if ((strng.length < 6) || (strng.length > 8)) {
       error = "The password is the wrong length. It must be 68 characters.\n";
    }
    else if (illegalChars.test(strng)) {
      error = "The password contains illegal characters.\n";
    }
    else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) &&
(strng.search(/(0-9)+/)))) {
       error = "The password must contain at least one uppercase letter, one
lowercase letter, and one numeral.\n";
    }
return error;
}

// verify email
function verify_email (strng) {
var error="";
if (strng == "") {
   error = "You didn't enter an email address.\n";
}

    var emailFilter=/^.+@.+\..$/;
    if (!(emailFilter.test(strng))) {
       error = "Please enter a valid email address.\n";
    }
    else {
//test email for illegal characters
       var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
         if (strng.match(illegalChars)) {
          error = "The email address contains illegal characters.\n";
       }
    }
return error;
}

// verify phone number - strip out delimiters and verify for 10 digits
function verify_phone (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a phone number.\n";
}
//strip out acceptable non-numeric characters
var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');
    if (isNaN(parseInt(stripped))) {
       error = "The phone number contains illegal characters.";

    }
    if (!(stripped.length == 10)) {
    error = "The phone number is the wrong length. Make sure you included an area
code.\n";
    }
return error;
}

 


Last Updated ( Sunday, 08 July 2007 )
 
< Prev   Next >