Filtering Even Basic Values

HTML form elements have no types associated with them, and most pass strings (which may represent things such as dates, times, or numbers) to the server. Thus, if you have a numeric field, you cannot assume that it was entered as such. Even in environments where powerful client side code can try to make sure that the value entered is of a particular type, there is no guarantee that the values will not be sent to the server directly, as in the "Double Checking Expected Values" section.

An easy way to make sure that a value is of the expected type is to cast or convert it to that type and use it, as follows:

$number_of_nights = (int)$_POST['num_nights'];

if ($number_of_nights == 0)
{
echo "ERROR: Invalid number of nights for the room!";
exit;
}

If we have the user input a date in a localized format, such as "mm/dd/yy"' for users in the United States, we can then write some code to verify it using the PHP function called checkdate. This function takes a month, day, and year value (4-digit years), and indicates whether or not they form a valid date:

// split is mbcs-safe via mbstring (see chapter 5)

$mmddyy = split($_POST['departure_date'], '/');
if (count($mmddyy) != 3)
{
echo "ERROR: Invalid Date specified!";
exit;
}

// handle years like 02 or 95
if ((int)$mmddyy[2] <> 50)
$mmddyy[2] = (int)$mmddyy[2] + 1900;
else if ((int)$mmddyy[2] >= 0)
$mmddyy[2] = (int)$mmddyy[2] + 2000;

// else it's <>

By taking the time to filter and validate the input, we can not only help ourselves out for natural error-checking that we should be doing in the first place (such as verifying whether a departure date for a plane ticket is a valid date), but we can also improve the security of our system.

1 komentar:

Unknown said...

Hi, nice description.Thanks for your help..

-Aparna
Theosoft

top