Data validation is an integral part of working with forms. Not only can invalid submitted data lead to security problems, but it can also break your webpage. Today, we'll take a look at how to remove illegal characters and validate data by using the "filter_var" function.
An example can be seen below. A user has entered the text "I don't have one" as their home page. If this data were to be entered into a database and then later retrieved as a link, the link would be broken.

Most people tend to think of data validation as an immensely tedious process where one either:
- Compares the data they want to validate against every possible combination they can think of.
- Tries to find a golden Regular Expression that will match every possible combination.
- A combination of the two.
There are obvious problems with the above listed:
- It's absolutely time consuming.
- There is a very high chance of error.
Fortunately, beginning with version 5.2, PHP has included a great function called filter_var that takes away the pain of data validation.
filter_var In Action
filter_var will 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.
Note: why sanitize and not just validate? It's possible the user accidentally typed in a wrong character or maybe it was from a bad copy and paste. By sanitizing the data, you take the responsibility of hunting for the mistake off of the user.
How to use filter_var
Using filter_var is incredibly easy. It's simply a PHP function that takes two pieces of data:
- The variable you want to check
- The type of check to use
For example, the below code will remove all HTML tags from a string:
$string = "<h1>Hello, World!</h1>"; $new_string = filter_var($string, FILTER_SANITIZE_STRING); // $new_string is now "Hello, World!"
Here's another example -- this time more difficult. The below code will ensure the value of the variable is a valid IP address:
$ip = "127.0.0.1"; $valid_ip = filter_var($ip, FILTER_VALIDATE_IP); // $valid_ip is TRUE $ip = "127.0.1.1.1.1"; $valid_ip = filter_var($ip, FILTER_VALIDATE_IP); // $valid_ip is FALSE
That's how simple it is to use filter_var. For a complete list of all the rules you can check against, see the end of this tutorial.
Sanitizing Example
Below is a quick example of sanitizing input from two fields: an email field and a home page field. This example will remove any characters that should not occur in either type of data.
<?php
if (isset($_POST['email'])) {
echo filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
echo "<br/><br/>";
}
if (isset($_POST['homepage'])) {
echo filter_var($_POST['homepage'], FILTER_SANITIZE_URL);
echo "<br/><br/>";
}
?>
<form name="form1" method="post" action="form-sanitize.php">
Email Address: <br/>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/> <br/><br/>
Home Page: <br/>
<input type="text" name="homepage" value="<?php echo $_POST['homepage']; ?>" size="50" /> <br/>
<br/>
<input type="submit" />
</form>

By using the FILTER_SANITIZE_EMAIL and FILTER_SANITIZE_URL constants definited by PHP, the guess work of knowing what characters are illegal is gone.
Validating Example
Just because the data is sanitized does not ensure that it's properly formatted. In the example below, the data did not need to be sanitized, but it's obvious that the user input is not an email or url.

In order to ensure the data is properly formatted, it needs to be validated.
<?php
if (isset($_POST['email'])) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "$email is a valid email address.<br/><br/>";
} else {
echo "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
}
if (isset($_POST['homepage'])) {
$homepage = filter_var($_POST['homepage'], FILTER_SANITIZE_URL);
if (filter_var($homepage, FILTER_VALIDATE_URL)) {
echo "$homepage is a valid URL.<br/><br/>";
} else {
echo "$homepage is <strong>NOT</strong> a valid URL.<br/><br/>";
}
}
?>
<form name="form1" method="post" action="form-validate.php">
Email Address: <br/>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/> <br/><br/>
Home Page: <br/>
<input type="text" name="homepage" value="<?php echo $_POST['homepage']; ?>" size="50" /> <br/>
<br/>
<input type="submit" />
</form>

Now that the data has been validated, you can be sure that the information submitted is exactly what you're looking for.
Putting It All Together: An Email Submit Form
Now that data sanitation and validation have been covered, we'll put those skills to use with a quick email submission form. This will by no means be of production quality -- for example, no form should require a home page -- but it'll work perfect for this tutorial. The form will take 4 pieces of information:
- Name
- Email Address
- Home Page
- Message
We'll sanitize and validate against all 4 pieces of data and only send the email if they are all valid. If anything is invalid, or if any fields are blank, the form will be presented to user along with a list of items to fix. We'll also return the sanitized data to the user in case they are unaware that certain characters are illegal.
Step 1 - Creating the Form
For the first step, simply create a form element with 5 fields: the for listed above and a submit button:
<form name="form1" method="post" action="form-email.php">
Name: <br/>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="50" /><br/><br/>
Email Address: <br/>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/> <br/><br/>
Home Page: <br/>
<input type="text" name="homepage" value="<?php echo $_POST['homepage']; ?>" size="50" /> <br/><br/>
Message: <br/>
<textarea name="message" rows="5" cols="50"><?php echo $_POST['message']; ?></textarea>
<br/>
<input type="submit" name="Submit" />
</form>
Step 2 - Determine if the Form was Submitted
You can check to see if a form was submitted by seeing if the submit button was "set". Place the following code above your form:
if (isset($_POST['Submit'])) {
}
Step 3 - Validating the Name and Message Field
Since both the name and message fields will be sanitized and validated the same, we'll do them together. First, check to see if either field is blank by doing the following:
if ($_POST['name'] == "") if ($_POST['message'] == "")
Next, sanitize them with the FILTER_SANITIZE_STRING constant
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING); $_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
Finally, check to make sure that the two fields still are not blank. This is to ensure that after removing all illegal characters, you are not left with a blank field:
if ($_POST['name'] == "") if ($_POST['message'] == "")
We won't do any validation on these two fields simply because there is no absolute way to validate against a Name or arbitrary message.
The final code looks like this:
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
if ($_POST['message'] != "") {
$_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if ($_POST['message'] == "") {
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
Step 4 -- Validate the Email Field
The email field will be sanitized and validated just as it was earlier in the tutorial.
First, check to make sure it is not blank:
if ($_POST['email'] != "")
Next, sanitize it:
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
Finally, validate it as a true email address:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
The final code looks like this:
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
Step 5 -- Validate the Home Page Field
Again, the home page field will be sanitized and validated the same way as earlier in the tutorial.
First, make sure it is not blank:
if ($_POST['homepage'] != "")
Next, sanitize it and remove any illegal characters:
$homepage = filter_var($_POST['homepage'], FILTER_SANITIZE_URL)
Finally, validate it to make sure it's a true URL:
if (!filter_var($homepage, FILTER_VALIDATE_URL))
The final code looks like this:
if ($_POST['homepage'] != "") {
$homepage = filter_var($_POST['homepage'], FILTER_SANITIZE_URL);
if (!filter_var($homepage, FILTER_VALIDATE_URL)) {
$errors .= "$homepage is <strong>NOT</strong> a valid URL.<br/><br/>";
}
} else {
$errors .= 'Please enter your home page.<br/>';
}
Step 6 -- Check for Errors and Send the Message
Now that we've gone through all fields, it's time to either report the errors or send the message. Start off by assuming there were no errors:
if (!$errors) {
Then build the email message:
$mail_to = 'me@somewhere.com'; $subject = 'New Mail from Form Submission'; $message = 'From: ' . $_POST['name'] . "\n"; $message .= 'Email: ' . $_POST['email'] . "\n"; $message .= 'Homepage: ' . $_POST['homepage'] . "\n"; $message .= "Message:\n" . $_POST['message'] . "\n\n";
And finally, send the message:
mail($to, $subject, $message);
However, if there were any errors, report them and have the user try again:
echo '<div style="color: red">' . $errors . '<br/></div>';
The completed project looks like this:
<?php
if (isset($_POST['Submit'])) {
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
if ($_POST['homepage'] != "") {
$homepage = filter_var($_POST['homepage'], FILTER_SANITIZE_URL);
if (!filter_var($homepage, FILTER_VALIDATE_URL)) {
$errors .= "$homepage is <strong>NOT</strong> a valid URL.<br/><br/>";
}
} else {
$errors .= 'Please enter your home page.<br/>';
}
if ($_POST['message'] != "") {
$_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if ($_POST['message'] == "") {
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
if (!$errors) {
$mail_to = 'me@somewhere.com';
$subject = 'New Mail from Form Submission';
$message = 'From: ' . $_POST['name'] . "\n";
$message .= 'Email: ' . $_POST['email'] . "\n";
$message .= 'Homepage: ' . $_POST['homepage'] . "\n";
$message .= "Message:\n" . $_POST['message'] . "\n\n";
mail($to, $subject, $message);
echo "Thank you for your email!<br/><br/>";
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
}
}
?>
<form name="form1" method="post" action="form-email.php">
Name: <br/>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="50" /><br/><br/>
Email Address: <br/>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/> <br/><br/>
Home Page: <br/>
<input type="text" name="homepage" value="<?php echo $_POST['homepage']; ?>" size="50" /> <br/><br/>
Message: <br/>
<textarea name="message" rows="5" cols="50"><?php echo $_POST['message']; ?></textarea>
<br/>
<input type="submit" name="Submit" />
</form>
Summary
I hope reading this tutorial gave you a good introduction to PHP's new data filtering features. There are still many more functions and rules that were not covered, so if you're interested in learning more, please see the Data Filtering section in the PHP manual.
- Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
Related Posts
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.











User Comments
( ADD YOURS )TJ January 15th
Pretty good article, Joe. This should be very helpful for people new to PHP.
However, I am an advocate of learning regular expressions, so this function seems like an easy way to opt out from doing more controlled work…
( )pixelsoul January 15th
Interesting.
I agree with TJ however.
( )Miles Johnson January 15th
Never used filter_var but it looks to be very promising.
I would probably wrap this in an OOP class and stay away from modifying the $_POST vars after the initial post.
( )Hasanga January 15th
wow! nice tutorial.
One quick thing…
I might make the $errors an array and fill the the array with a proper index.
So that I can display a much descriptive error message to the user.
Anyway good tut! keep em coming!
( )insic January 16th
wow nice tutorial. its been a while looking an excellent example like this using php filters.
( )Stephen Coley January 16th
I just tested this out, and it seems that it would hold up pretty well against an sql injection.
It’s a bit annoying that ‘www.google.com’ wouldn’t match a valid url. The mandatory http:// is a bit much, but I understand why that check is in place.
Good tutorial, none the less.
( )kaqfa January 16th
i always find a best way to make form validation,
this far i prefer to use double validation both in client (with javascript) and server side.
more user friendly and secure i thing, and of course more difficult
( )Adam January 16th
@Stephen; You can just put the http:// as a the fields default value, and it will be fine.
I’ve been looking for something like this for a user login ive built, i’ll try and adapt it to what i have and see what happens.
Thanks.
( )iEthan January 16th
This is really nice. I can definitely implement this in my sites.
( )Jack F January 16th
@Stephen – You could also figure out if the field has http:// in it – and add it if it does not.
Good tutorial, neve knew this method existed!
( )M.A.Yoosuf January 16th
its simply nice flow. its very good idea for back end validation, thank you buddy
( )Ed Baxter January 16th
Nice Method
( )Xobb January 16th
I would recommend using the OOP approach for data validation. Also I don’t find it correct to merge sanitation and validation similar process. As far as I understand sanitation is the process of filtering improper content (such as javascript or other XSS stuff).
There is a nice tool for data sanitation named HTMLpurifier, but it works with PHP 5 only.
( )organicIT March 21st
Xobb Thanks for the purifier tip. it is as sweet as the cheeba flowing through the Graffix.
( )steve January 16th
Step 2 – Determine if the form was submitted – it’s better to create a hidden text field and see if THAT one was submitted, rather than the submit button itself; this prevents errors in IE when the user presse “enter” to submit the form.
( )frank katzer | 1klang.de internetagentur January 16th
perfect. thank you for this timesaving article.
( )@Xobb: thanks for the purifier recommendation!
Jash Sayani January 16th
Thanks Xobb. HTML Purifier is great!!
( )Timothy January 16th
Very useful. Thanks for the post. I’m always happy to hear about some PHP functions
( )Robert January 16th
The Filter extension goes way beyond filter_var. I suggest reading the Filter book http://www.php.net/manual/en/book.filter.php first.
You don’t filter POST and GET with filter_var, but with filter_input. Yet again, refer to the manual.
The URL validation is kinda bogus a bit, but I’m sure they will improve it in future releases.
( )Fatigo January 16th
This is a wrong and an unsafe way! Don’t use it for real life applications!
( )Tarandon January 16th
Just be careful not to infringe on the recently granted IBM patent for clearing lead and trailing spaces. Un-believable.
http://techdirt.com/articles/20090108/0230453331.shtml
( )Chris Gedrim January 16th
@Fatigo if your going to flame the content of the article at least back it up with some reasoning / examples. You’re comment is of no use to anyone!
I personally do some client side validation with a little help from jQuery before doing any server-side validation; it just prevents extra, un-needed, network traffic. (Just remember to make it degrade gracefully though!)
( )Joe Topjain January 16th
Hey, I just noticed my tutorial was posted! Thank you everyone for the comments.
@TJ, @pixelsoul: the FILTER_VALIDATE_REGEXP might interest you. It allows you to validate data against any regular expression you make.
@Hasanga, @steve: absolutely. The email submit exercise was just a light example. By no means is it production quality. @Robert is on the right track with the other functions.
( )jerichvc January 16th
very practical, thanks.
( )Chris Gunther January 16th
Nice tutorial. Let’s see more like this.
( )Nusrat Ali Bangash January 16th
One of the good tutorial , but i dont understand why some people
has some objecyions on it , like this is not safe etc.
if it is true plz inform us ok.
Thanks
( )Player January 17th
WoW! Nice! So simple! Thanks!
BTW…”mail($to, $subject, $message);” don’t should be “mail($mail_to, $subject, $message);” ? =|
maybe i’m wrong…
( )Bari January 17th
Great tutorial. It will be of great use in a real life work.
( )The first time I tried to use filter_var, I got a “call to undefined function” error – yeah, that was a try on a server with old PHP4. But PHP5 is used almost everywhere now so this is quite handy against all those email validators,form validators etc.
Joe Topjain January 17th
@Player: You’re absolutely right. Thanks for catching that.
( )George January 17th
Like most of the code on here and other tutorial sites, this is written to demonstrate proof-of-concept and is not something you should copy, paste and launch.
Still, I think a lesson about how to use regular expressions for handling this sort of stuff would be more valuable and could provide more control and flexibility.
For example, the URL filtering is remarkably… Lame. You could provide “http://www.google.com” and “google://google.google” and they would validate the same using filter_var. It might not be a vulnerability that anyone can take advantage of (The required ‘//’ effectively comments out anything you’d try to do with “javascript://” – I tried it) but it still seems silly to leave those opportunities for human error when they could be removed so easily.
( )Thomas Winsnes January 17th
A little warning
It seems that all FILTER_VALIDATE_URL is doing is calling parse_url(), which makes it effectively useless since parse_url() only fails on really malformed urls.
$url = ‘http://…’;
var_dump(filter_var($url, FILTER_VALIDATE_URL));
Will display: string(10) “http://…”
None of the flags help either, so you’re better off with regular expressions to validate a url.
( )Julio Fagundes January 18th
Nice man!!
thanks a lot.
( )Peter January 18th
As useful as filtering is, it is only one step in the right direction. A particular example would be that FILTER_SANITIZE_EMAIL wouldn’t strip any characters from, and FILTER_VALIDATE_EMAIL would return intact (i.e., not FALSE and therefore valid) when provided with the email address %@0.- (in case that gets mungled for whatever reason it’s: percent at zero dot dash) to name one of many valid emails that your application probably won’t want to accept.
( )mamjed January 18th
man if some one could write a follow up on how to integrate validation scripts with jquery to fade the error message in and stuff like that.
( )Nebu Sebu January 19th
Thanks dude… this was really helpfull… Thanks a lot keep up.
( )Araba Oyunları January 19th
Good Article, Thanks
( )Lee January 19th
Dude….. nice stuff! I need to rewrite some functions to use this…
thanks for the article
( )Didik Wicaksono January 20th
Is there any jQuery techniques similar to these?
( )Eduardo January 20th
Very cool, but I think it’s more secure to use regular expressions. We can create them and save as a snippet to use everytime we want.
( )MightyUhu January 21st
The function is useful if you want to do validation to see wheter the user input is valid or not.
( )But I dont see many sense in the process of sanatizing data, before validating: Either the input of the user is valid or it isn’t. It’s simple as that. I can see no sense in putting some semi-valid data, which has passed my validation after sanatizing into my datasource or whatever.
Correct me if i’m wrong
Steve rynk January 22nd
Very cool article! very helpfull stuff. @ MightyUhu i think you’re right, it doesn’t make sense,does it?
( )Taylor Satula January 24th
Tut was ok, but the clip icon was really funny
( )Dan February 14th
For HTML standardization or filtering and security, PHP application developers can try htmLawed: http://bioinformatics.org/phplabware/internal_utilities/htmLawed
( )Bharathi March 11th
The validation done in server side… if i validate the form at client side what was the easy method? can you pls reply me.
( )Muhammad Adnan March 14th
HTMLpurifier is a good tool .
( )Steve March 21st
great article. Have already implemented concept based on reading this tutorial. Thanks very much.
( )Araba Oyunları March 24th
Thank you , very good
( )Oyunlar1 March 24th
thanks admin
( )Shahriat Hossain June 4th
Wow this is really awesome and so short for filtering out the inputs and I have never been used this function before, really I am digging into the web in the right way, thanks for sharing your knowledge
( )Directoryvirgin June 14th
Thanks for providing the tutorial, im glad that each time i read the comments afterwards, helps during the learning process even more as i see people pointing out how they may do it differently or why something may not be neccessary.
( )Jaspal Singh August 8th
filter_var, great way to sanitize & validate in php5.
( )Thanks for sharing.
taba August 22nd
Good Stuff
( )Araba Oyunları September 15th
thanks !! very helpful plugin
( )Araba Oyunları September 28th
Thanks for nice posting and usefull message
( )Forum October 11th
woows. Thanks
( )