Validating and Sanitizing Form Input in PHP
Validation means check whether the field is filled or not in the proper way. There are two types of validation are available in PHP.
- Client-Side Validation: Validation is performed on the client machine web browsers.
- Server-Side Validation: Validation is performed on the server machine.
Some of validation rules for field:
| Field | Validation Rules |
| Name | Should required letters and white-spaces |
| Should required @ and . | |
| Website | Should required a valid URL |
| Radio | Must be selectable at least once |
| Check Box | Must be checkable at least once |
| Drop Down menu | Must be selectable at least once |
Validating: Check User Input
To validate is to ensure the data you've requested of the user matches what they've submitted.
<input type="text" id="my-zipcode" name="my-zipcode" maxlength="5"/>Just like \hat, we've told the browser to only allow up to five characters of input, but there's no limitation on what characters they can input.
They could enter "11221" or "eval". If we're sari ng to the database, there’s no way we want to give the user unrestricted write access.
This is where validation plays a role. When processing the form, we'll write code to check each field for its proper data type. If it's not of the proper data type, we'll discard it.
Sanitizing: Cleaning User Input
Sanitization is a bit more liberal of an approach to accepting user data. We can fall back to using these methods when there's a range of acceptable input.
For example in bellow field , we want prevent from XSS.
<input type="text" id="titIe" name="title" />Escaping: Securing Output
For security on the other end of the spectrum, we have escaping. To escape is to take the data you may already have and help secure it prior to rendering it for the end user.
hlmlSpecialChars()
urIEncodeExample:
function clean data($data) (
$data = trim($data);
$data = stripsIashes($data);
$data = htmIspeciaIchars($data);
return $data;
}Validation vs Sanitization
- validation, as it happens before sanitization
- validation is verifying thot the data being submitted conforms to a rule or set of rules you (the developer) set for a particular input field.
- Whereas validation requires user input to conform to a certain rule or rules put forth by the developer, sanitization only cares about making sure the data being submitted doesn't contain code.
filter_var() Method
filter_var with do, both, sanitize and validate data. What's the difference between the two?
- Sanitizing will remove any illegal character from the data.
- Validating will determine if the data is in proper form.
filter_var($ip, FILTER_VALIDATE_IP); // return boolean
fiIter_var($email, FILTER_VALIDAT_EMAIL); // return boolean
filter_var($homepage, FILTER_VALIDATE_URL); // return boolean
fiIter_var($strIng, FILTER_SANITIZE_STRING);
filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
fiIter_var($_POST['homepage'], FILTER_SANITIZE_URL);Validate URL:
The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:
<?php
$website = input($_POST["site"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-
a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
?>Above syntax will verify whether a given URL is valid or not. It should allow some keywords as https, ftp, www, a-z, 0-9,..etc.
Validate E-mail
The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
<?php
$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
}
?>Validate Name
The code below shows a simple way to check if the name field only contains letters and whitespace.
If the value of the name field is not valid, then store an error message:
<?php
$name = $_POST["name"];
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
echo " Name : Only letters and white space allowed";
}
?>The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.