Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Validating Input

Any sensible site should include server-side validation of variables, because they are much harder to hack, and they will work no matter what browsers your visitors are using.

Basic input validation in PHP is done using the functions is_string(), is_numeric(), is_float(), is_array(), and is_object(). Each of these functions take just one parameter, a variable of their namesake, and return true if that variable is of the appropriate type. For example, is_numeric() will return true if the variable passed to it is a number, and is_object() will return true if its variable is an object. There is one other function of this type that works the same way but is useless for validation, and that is is_resource()—it's mentioned here for the sake of completeness.

The three basic validation checks you should conduct on input are whether you have each of your required variables, whether they have a value assigned, and whether they are of the type you were expecting. From there, you can conduct more complicated checks, such as whether the integer values are in the range you would expect, whether the string values have enough characters, whether the arrays have enough elements, etc.

Here are some examples:

 // is the $Age variable set with a numeric value between 18 and 30? if (isset($Age)) { if (is_numeric($Age)) { if (($Age > 18) && ($Age < 30)) { // input is valid } else { print "Sorry, you're not the right age!"; } } else { // empty or non-numeric print "Age is incorrect!" } } ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page