


1. The trim() function
2. The strpos() function
3. The stristr() function
4. The preg_match() function
5. Conclusion.
1. The trim() function
This the simplest step to making sure that your user input is correct, and contains something. It will basically
remove any white space (i.e. space/return) from the beginning and end of the input. If you don't do this, then the
user could potentially just put a space in, and PHP wouldn't know the difference.
<?
/* Sets variable equal to what the user put in the "name" element of your form, and trims it. */
$user_name = trim($_POST['name']);
/* if ($user_name is not equal to 0)... By not equal to 0, I mean, is there actually something there */
if(!$user_name){
die('Please enter a name!');
}else{
/* Something was there */
echo 'Username accepted.';
}
?>
2. The strpos() function
This function finds a single character within a string, and returns its position. If the character is not there, it returns false.
To use it, you just need to think of a character that would have to be in the string to make sure it's valid (i.e. in an e-mail address, you need the @ character).
<?
/* if (the position of the @ sign in $_POST['email'] is not 0)... */
if(strpos($_POST['email'], '@')){
echo 'Congrats, you have an @ in your e-mail address.';
}else{
/* @ was not found */
die('Invalid e-mail, please try again.');
}
?>
3. The stristr() function
This function is a little more complex then the strpos() function, because it matches a string within a string, and is case insensitive.
Other then that it functions pretty much the same.
<?
/* if (the string "foo", "Foo", "fOo", etc, is in $_POST['text'])... */
if(stristr($_POST['text'], 'foo')){
echo 'You\'ve got foo in text.';
}else{
die('There\'s no foo in this text.');
}
?>
4. The preg_match() function
This is by far the most complex of functions used for string comparison. It is by no means to be used by the timid due
to the fact that if you don't know what you're doing, you won't get anything done. The complete set of rules for it
can be found by clicking the preg_match() link above. Other then that, it still functions similar to the 2 functions above,
the major difference being, how it looks for stuff, and what it returns. This returns the number of times a pattern matches,
that being either 0 times (no match) or 1 time because preg_match() will stop searching after the first match.
Example:
<?
/* if (the case insensitive pattern was found within $_POST['text'], set array $match equal to what was found)... */
if(preg_match('#http://(www.|)[a-z1-9_\-]+\.com#i', $_POST['text'], $match)){
echo 'A match was found in the text.<br>Text found: '.$match[0];
}else{
die('No text was found that matched the pattern.');
}
?>
Conclusion
The above are all methods you can use to validate form input. There are more ways in which you can do that,
it all depends on how creative you are. Below is a sample form you can use to test the above scripts.
Enjoy.