Arrow

Simple PHP form validation with ctype_alnum

First published on January 1, 2007

The key to form security is (as I’m learning) to validate, validate, validate. If you are having users input data for processing by the server, hackers are adept at writing all sorts of code into the form fields that will… do all sorts of mean things.

Here’s a really handy way to validate simple form variables where you only want to allow certain characters. For example, for user names on a registration form you might only want to allow letters, numbers, and underscores.

ctype_alnum is a nice little function built into PHP that will check that only letters and numbers exist in a given variable. With the help of str_replace, you can allow any extra characters you want.

JavaScript (which I won’t talk about here) is also handy as it will give users pop-up warnings before a form is processed, but hackers can simply disable JavaScript in their browsers. Thus, you need a solution to validate a form field after it’s been submitted.

You would place the following PHP code into the file that processes the form variables:

// get the variable, as usual
// if you#039;re allowing apostrophes or quotation marks, you might have to use stripslashes here
$yourvariable = $_POST[#039;yourvariable#039;];

// define here what extra characters you want to allow, all separated by commas
// in this example, we are allowing dashes, underscores, and exclamation marks
$extra = array(#039;-#039;, #039;_#039;, #039;!#039;);

// if $yourvariable has characters other than letters, numbers, and those defined in $extra, don#039;t allow the form to process any further
// that 'p' character can actually be any letter or number
if(!ctype_alnum(str_replace($extra, #039;p#039;, $yourvariable))) {
die ("Sorry, you entered some invalid characters. Please remove them before submitting again.");
}
Arrow

2 Responses to “Simple PHP form validation with ctype_alnum”


  1. jenny says:

    I don’t understand this. Where is the variable $extra used? Where does the variable $chars come from? And then you don’t loop, but check for a single instance..?


  2. Peter says:

    Oops, in my infinite stupidity, I failed to properly name the variables. It should only be $extra (fixed now)…

    Also, you don’t have to loop when looking at one variable because ctype_alnum looks at the entire variable.

Speak your mind

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word