$is_alpha = ctype_alpha($input);
$is_integer = ctype_digit($input);
$is_alphanumeric = ctype_alnum($input);
Finally, for more advanced filtering and validation, the PCRE (Perl-Compatible
Regular Expression) extension
is a fairly powerful and flexible tool. It requires
knowledge of regular expressions, but the extensions manual section includes
everything you need to know to get started. Here are examples to filter and validate
alphanumeric strings:
$input_sanitized = preg_replace('/[^A-Za-z0-9]/', '', $input);
$input_is_valid = (bool) preg_match('/^[A-Za-z0-9]$/', $input);
For an excellent reference on regular expressions, check out Mastering Regular Ex-
pressions by Jeffrey E.F. Friedl (Sebastopol: OReilly, 2006).
Other methods of filtering input that are specific to the intended usage of that input
will be covered later in this chapter. Escaping output is covered shortly.
Cross-site Scripting
For cross-site scriptingcommonly abbreviated as XSSthe attack vector targets
an area where a user-supplied variable is included in application output, but not
properly escaped. This allows an attacker to inject a client-side script of their choice
as part of that variables value. Heres an example of code vulnerable to this type
of attack:
<form action=<?php echo $_SERVER['PHP_SELF']; ?>>
<input type=submit value=Submit />
PHP Master: Write Cutting-edge Code176

Get PHP Master now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.