Logo         Community
  Trog
Services
The Company
Community
Columns
Your Account
Contact Us
 
 
PHP 101 (part 13): The Trashman Cometh
Secure your PHP scripts with clever input validation tricks.

| The Dating Game |

Validating dates is another important aspect of input validation. It's all too easy, given a series of drop-down list boxes or free-form text fields, for a user to select a date like 29-Feb-2005 or 31-Apr-2005, neither of which is valid. Therefore, it's important to check that date values provided by the user are valid before using them in a calculation.

In PHP, this task is significantly simpler than in other languages, because of the checkdate() function. This function accepts three arguments - month, day and year - and returns a Boolean value indicating whether or not the date is valid. The following example demonstrates it in action:


<html>
<head></head>
<body>
<?php
if (!isset($_POST['submit'])) {
?>
    <form action = '<?php $_SERVER['PHP_SELF']?>' method = 'post'>
    Enter your date of birth:
    <br /><br />
    <select name = 'day'>
    <?php
    // generate day numbers
    for ($x = 1; $x <= 31; $x++) {
        echo "<option value = $x>$x</option>";
    }
    ?>
    </select>
    <select name = 'month'>
    <?php
    // generate month names
    for ($x = 1; $x <= 12; $x++) {
        echo "<option value=$x>".date('F', mktime(0, 0, 0, $x, 1, 1)).'</option>';
    }
    ?>
    </select>
    <select name = 'year'>
    <?php
    // generate year values
    for ($x = 1950; $x <= 2005; $x++) {
        echo "<option value=$x>$x</option>";
    }
    ?>
    </select>
    <br /><br />
    <input type = 'submit' name = 'submit' value = 'Save'>
    </form>
<?php
}
else {
    // check if date is valid
    if (!checkdate($_POST['month'], $_POST['day'], $_POST['year'])) {
        die("ERROR: The date {$_POST['day']}-{$_POST['month']}-{$_POST['year']} doesn't exist!");
    }

    // process the data
    echo "You entered {$_POST['day']}-{$_POST['month']}-{$_POST['year']} - which is a valid date.";
}
?>
</body>
</html>


Try entering an invalid date, and see how PHP calls you on it. Ain't that cool?

If you're storing date input in a MySQL table, it's interesting to note that MySQL does not perform any rigorous date verification of its own before accepting a DATE, DATETIME or TIMESTAMP value. Instead, it expects the developer to build date verification into the application itself. The most that MySQL will do, if it encounters an obviously illegal value, is convert the date to a zero value - not very helpful at all! Read more about this at http://dev.mysql.com/doc/mysql/en/datetime.html.

While we're on the topic, let's talk a little bit more about multiple-choice form elements like drop-down list boxes and radio buttons. In cases where it's mandatory to make a choice, a developer must verify that at least one of the available options has been selected by the user. This mainly involves clever use of the isset() and - for multi-select list boxes - the is_array() and sizeof() functions. The next example illustrates this:


<html>
<head></head>
<body>
<?php
if (!isset($_POST['submit'])) {
?>
    <form action = '<?php $_SERVER['PHP_SELF'] ?>' method = 'post'>
    Pizza base:
    <br />
    <input type = 'radio' name = 'base' value = 'thin and crispy'>Thin and crispy
    <input type = 'radio' name = 'base' value = 'deep-dish'>Deep-dish
    <br />
Cheese:
    <br />
    <select name = 'cheese'>
        <option value = 'mozzarella'>Mozzarella</option>
        <option value = 'parmesan'>Parmesan</option>
        <option value = 'gruyere'>Gruyere</option>
    </select>
    <br />
    Toppings:
    <br />
    <select multiple name = 'toppings[]'>
        <option value = 'tomatoes'>Tomatoes</option>
        <option value = 'olives'>Olives</option>
        <option value = 'pepperoni'>Pepperoni</option>
        <option value = 'onions'>Onions</option>
        <option value = 'peppers'>Peppers</option>
        <option value = 'sausage'>Sausage</option>
        <option value = 'anchovies'>Anchovies</option>
    </select>
    <br />
    <input type = 'submit' name = 'submit' value = 'Save'>
    </form>
<?php
}
else {
    // check radio button
    if (!isset($_POST['base'])) {
        die('You must select a base for the pizza');
    }

    // check list box
    if (!isset($_POST['cheese'])) {
        die('You must select a cheese for the pizza');
    }

    // check multi-select box
    if (!is_array($_POST['toppings']) || sizeof($_POST['toppings']) < 1) {
        die('You must select at least one topping for the pizza');
    }

    // process the data
    echo "One {$_POST['base']} {$_POST['cheese']} pizza with ";
    foreach ($_POST['toppings'] as $topping) echo $topping.", ";
    echo "coming up!";

}
?>
</body>
</html>


Nothing to tax your brain too much here - the isset() function merely checks to see if at least one of a set of options has been selected, and prints an error message if this is not the case. Notice how the multi-select list box is validated: when the form is submitted, selections made here are placed in an array, and PHP's is_array() and sizeof() functions are used to test that array and ensure that it contains at least one element.


How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.

Read more, or grab your copy now!


previous page more like this  print this article  next page
 
Search...
 
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
more...
 
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
more...
 
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
more...
 
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
more...
 
In cut!...
American Chai
The Core
Possession
more...
 
Find out how you can use this article on your own Web site!


Copyright © 1998-2018 Melonfire. All rights reserved
Terms and Conditions | Feedback