PHP 4: Validating Forms

Data sent from to a script should be checked to make sure that it is not empty or of the wrong type e.g. numeric. PHP provides a number of functions to assist with this.

Stripslashes($variable)

PHP includes a feature called Magic Quotes, which automatically escapes quotation marks in text and inserts a backslash character in front of them. This is useful where data is to be used in a url or stored in a database but a small problem arises where the contents of a variable are to be displayed. If a user includes a quotation mark in a form field such as comments and this is passed to a variable for display then the backslash charcater will also appear. To prevent this use the stripslashes function:

$variable=stripslashes($variable)

This will remove the backslashes automatically inserted by Magic Quotes. This might be particularly useful in a $comments field where the user has the freedom to compose messages.

Trim($variable)

Another useful function is trim($variable), which removes blank spaces from the front and rear of text:

$variable=trim($variable)

Isset($variable)

To determine whether a variable derived from a form has a value use the isset($var) function. This checks to see whether a variable has a value, including 0 but not NULL or FALSE.

Strlen($variable)

The isset($variable) function does not recognise empty strings so instead we can use the strlen($variable) function:

if strlen($variable) > 0 {>br> //$variable includes at least one character
} else {
//$variable is empty {
}

Try it!

Home