13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

370 Chapter 16 <strong>Web</strong> Application Security<br />

There is a little bit more code involved here, but we can at least be sure we are getting<br />

correct values, <strong>and</strong> this becomes a lot more important when we start h<strong>and</strong>ling data<br />

values more financially sensitive than a user’s gender. As a rule, we cannot ever assume<br />

that a value from a form will be within a set of expected values—we must check first.<br />

Filtering Even Basic Values<br />

HTML form elements have no types associated with them <strong>and</strong> most simply pass strings<br />

(which may, in turn, represent things such as dates, times, or numbers) to the server.<br />

Thus, if you have a numeric field, you cannot assume or trust that it was truly entered as<br />

such. Even in environments where particularly powerful client-side code can try to make<br />

sure that the value entered is of a particular type, there is no guarantee that the values<br />

will not be sent to the server directly, as we saw in the previous section.<br />

An easy way to make sure that a value is of the expected type is to cast or convert it<br />

to that type <strong>and</strong> then use that value, as follows:<br />

$number_of_nights = (int)$_POST['num_nights'];<br />

if ($number_of_nights == 0)<br />

{<br />

echo "ERROR: Invalid number of nights for the room!";<br />

exit;<br />

}<br />

If we have the user input a date in some localized format, such as mm/dd/yy for users<br />

in the United States, we can then write some code to make sure it is a real date using<br />

the <strong>PHP</strong> function called checkdate.This function takes a month, day, <strong>and</strong> year value (4-<br />

digit years), <strong>and</strong> indicates whether they, combined, form a valid date:<br />

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

$mmddyy = split($_POST['departure_date'], '/');<br />

if (count($mmddyy) != 3)<br />

{<br />

echo "ERROR: Invalid Date specified!";<br />

exit;<br />

}<br />

// h<strong>and</strong>le years like 02 or 95<br />

if ((int)$mmddyy[2] < 100)<br />

{<br />

if ((int)$mmddyy[2] > 50)<br />

$mmddyy[2] = (int)$mmddyy[2] + 1900;<br />

else if ((int)$mmddyy[2] >= 0)<br />

$mmddyy[2] = (int)$mmddyy[2] + 2000;<br />

}<br />

// else it's < 0 <strong>and</strong> checkdate will catch it

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!