Home > PHP > Simplified PHP Input Validation for forms

Simplified PHP Input Validation for forms

When it comes to online forms, gathering information from the user is of utmost importance. That being said, one must ensure that the user enters the correct information in the form, especially from a security point of view…Input from users in a web form provides a direct avenue of attack into the application (just google SQL Injection).

Take a simplified, yet effective approach to input validtion with your web forms and PHP.

Take a simplified, yet effective approach to input validation with your web forms and PHP.

As far as input validation goes, most programmers prefer a proactive strategy: you determine what input you want to collect from the user (number format for ages, alpha characters for names, and so forth) and then you collect only that format, producing an error message when the user enters something else. However, some users quickly get frustrated when they have to re-enter the input again, or they can’t figure out what is causing the problem. To combat the inherent confusion of the user, why not run all input through a validation function that automatically searches for potentially harmful input, removes the offending characters, then continues to process the form? This is what we are going to do:

[php]
<?php

//When the form is submitted, our 2 form fields, username and password, will be purged of potentially harmful characters.
//In this case, the characters will be replaced with blank spaces.
if ($_POST) {

//Function to remove specific special characters
function cleanInput($text)
{
$code_entities_match = array(‘-’,'>’,'!’,'#’,'$’,'%’,'^’,'&’,'*’,'(‘,’)',’{‘,’}',’|',’:',’"’,'<’,’[',']‘,’\\’,';’,"’",’,',’/',’*',’~',’`');
$code_entities_replace = array(”,”,”,”,”,”,”,”,”,”,”,”,”,”,”,”,”,”);
$text = str_replace($code_entities_match, $code_entities_replace, $text);
return $text;
}
//Set form variables
$Username=stripslashes(cleanInput($_POST['username']));
$Password=stripslashes(cleanInput($_POST['password']));

//process your form variables as needed, as they have been sanitized with our cleanInput function.
//You can write the values to a database, send via an email script, and so forth.

}//End post
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="login" name="login">

<div class="label01">Username:</div>
<input type=text size=30 name="username" maxlength=30 />

<div class="label01">Password:</div>
<input type=password size=30 name="password" maxlength=30 />
<br />
<div id="submitButton">
<button type="submit" value="submit" name="submit" >Logon</button>

</div>

</form>
[/php]

Please read the script comments to see what is taking place. This is a rudimentary approach to input validation, but it works, is simple to initialize, and it will help to keep your data safe.

Thantos PHP

June 16th, 2009
  1. No comments yet.
  1. No trackbacks yet.