Ingenio Home  | Blog Policies  | Help
Welcome to Community Sign in | Join | Help

Expect the Unexpected

This one isn't easy...it takes a lot of practice to master, but the basic principle is simple:

When you write your code, write it to handle what it isn't designed to handle.

Here's an example:

Let's say you've got a form where you ask for a zipcode because you want to know if the user lives in Florida. Your PHP code might look something like this:

<?php
$ZipCode = $_REQUEST['zipCode'];
if ( $ZipCode >= 32000 || $ZipCode <= 34000 ) {
    echo "You live in Florida!";
} else {
    echo "You live somewhere else!";
}
?>

But, we aren't doing any error checking. We need to make sure that the field has something in it, that it's a number, and that it's 5-9 digits in length. So, we need to adjust our code:

<?php
if ( ! isset( $_REQUEST['zipCode'] ) ) {
    echo "You didn't enter a Zip Code!";
} else {
    $ZipCode = $_REQUEST['zipCode'];
    if ( is_numeric( $ZipCode ) && strlen( $ZipCode ) >= 5 && strlen( $ZipCode ) <= 9 ) {
       if ( $ZipCode >= 32000 && $ZipCode <= 34000 ) {
          echo "You live in Florida!";
       } else {
          echo "You live somewhere else!";
       }
    } else {
       echo "You didn't enter a valid zipcode!";
    }
}
?>

Always try and anticipate what your users might do and write your script accordingly - otherwise not only do you risk an undesired effect, you might send your users nasty errors or even open up your website to hacking.

If you need your scripts proof-read, let me know!
Published Thursday, August 02, 2007 2:25 AM by The PHP Doctor

Comment Notification

Subscribe to this post's comments using RSS

Comments

No Comments

What do you think?

(required) 
(required) 
(required) 
Enter the numbers you see into the
field below.
(required)