Use your left/right keys to browse tutorials
PHP form validation

PHP form validation

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on March 6, 2009

When building a simple form, validation is usually neglected leaving us open to malicious attacks or genuine user error. filter_var is a built in function to PHP 5 that allows you to strip out any unwanted characters and also makes sure that the data is in the right format i.e. you can check to see if a users email address is in fact a valid email address or that a url is valid. It will also strip out any html tags for example if we submit in a form ‘<h1>My Name</h1>’ php will strip out the h1 tags and leave us with ‘My Name’.

Why not just use regular expression?

I use regular expression as well as this method I guess they both have their advantages, regular expression is great if you have a form that you are taking a specific data structure for example a number, then 3 letters, then 4 numbers, and 2 more letters. e.g. ’293afor4958dr’ you could easily user regex to determine the correct string structure.

Of course if you don’t have PHP 5 installed on your server you will have to use regex, i have a simple tutorial on how to use Regular expression with twitter here

Here is a quick form that I’ve put together that demonstrates how to validate data using filter_var in PHP 5. I’ve also put the errors in an array which i feel is the best way to render errors. This whole method of form validation is shorter and quicker than using regular expression and strip_tags.

The PHP code:


// this strips out any unwanted html tags and turns it into a string
 $_POST['fname'] = filter_var($_POST['fname'], FILTER_SANITIZE_STRING);
//if the text field is empty put the error in the array  
if ($_POST['fname'] == "") {  
       $errors[] = "Please enter your first name";

// this strips out any unwanted html tags and turns it into a string
 $_POST['lname'] = filter_var($_POST['lname'], FILTER_SANITIZE_STRING); 
//if the text field is empty put the error in the array  
if ($_POST['lname'] == "") {  
       $errors[] = "Please enter your last name";

// check to see if the website url is valid or not
if(!$_POST['website']){$errors[] = "your website address is needed";}else{
    $website = filter_var($_POST['website'], FILTER_SANITIZE_URL);
//if the text field is empty put the error in the array 	
    if (!filter_var($website, FILTER_VALIDATE_URL)) {
       $errors[] = "$website is <strong>NOT</strong> a valid URL.";

// if there the array has any values in it the echo them else process the form
		echo '<div class="error"><span>The following errors happened whilst processing your form!</span><ul>';
		while (list($key,$value) = each($errors))

			echo '<li>'.$value.'</li><br />';
	else {
	//submit the data to a database or process it further in our case we echo that the form was submitted ok and echo the data
	echo '<div class="ok">There were no errors and your form would normally be processed but this form does nothing!</div>';
	// echo the form data (this is where you'd put it in the database etc...) 
    echo 'This is what you entered. If you add any code tags they will be automatically stripped out!<br/><br/>';
	echo '<strong>First Name: </strong>'.$_POST['fname'].'<br/>'; 
	echo '<strong>Last Name: </strong>'.$_POST['lname'].'<br/>';
    echo '<strong>Web Address: </strong>'.$website.'<br/><br/>';


The HTML form:

<form method="post">
    First Name:
    <input class="element" name="fname" type="text" />
    Last Name:
    <input class="element" name="lname" type="text" />
    <input class="element" name="website" type="text" value="http://" />
    <input name="submit" type="submit" />


More tutorials from Papermashup
7 discussions around PHP form validation
  1. Mike says:

    Nice little form validation!

    One suggestion that I use would be to create sticky form fields if an error occurred. Using isset() in the form value=”" is the easiest way I’ve found!

  2. AzeriFire says:

    Hi again. I just wrote little function to check variables for isset and for not empty string. For sample we must check 7 variables which passed with POST method. We just check it with my function. Sample ( old style cheking)

    New style with my function:

    Really easy and less coding.Here more about this function ( at the end of post in English )

  3. AzeriFire says:

    I am sorry. There are must be if(isset(…)… My first code is wrong, must be:

  4. Ashley says:

    @azeriFire thanks for the kind words and its good to hear that someone reads my blog! :) Ashley

  5. AzeriFire says:

    All thanks to you for the great blog! ( I bookmark it and follow blog every day )

  6. Ashley says:

    @azeriFire great point and thanks again for the comments! ;) Ashley

  7. AzeriFire says:

    Hi. Thank you for tutorial. BTW, I think first thing to check , must be isset(POST['some_input_name']). I always check it firstly. May be POST['submit'] was sent from another server? ;) We dont want to display PHP errors to hackers ( OR to dummy user). As that one , we must be sure that, we get POST from our form. ( IMHO !)
    Sample here:

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.

What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.