Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 13. Security Methods > Validating Data by Type

Validating Data by Type

For the most part, the form validation used in this book thus far has been rather minimal, often just checking if a variable has any value at all. In many situations, this really is the best you can do. For example, there’s no perfect test for what a valid street address is or what a user might enter into a comments field. Still, much of the data you’ll work with can be validated in stricter ways. In the next chapter, the sophisticated concept of regular expressions will demonstrate just that. But here I’ll cover the more approachable ways you can validate some data by type.

Two Validation Approaches

A large part of security is based upon validation: if data comes from outside of the server—from HTML forms, the URL, cookies, it can’t be trusted. (A higher level of security also validates any data coming from outside of the script, including sessions and databases.) There are two types of validation: whitelist and blacklist. In the calculator example, we know that all values must be positive, that they must all be numbers, and that the quantity must be an integer (the other two numbers could be integers or floats, it makes no difference). Typecasting forces the inputs to be numbers, and a check confirms that they are positive. At this point, the assumption is that the input is valid. This is a whitelist approach: these values are good; anything else is bad.

The preventing spam example uses a blacklist approach. That script knows exactly which characters are bad and invalidates input that contains them. All other input is considered to be good.

Many security experts prefer the whitelist approach, but it can’t always be used. Each example will dictate which approach will work best, but it’s important to use one or the other. Don’t just assume that data is safe without some sort of validation.



  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint