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:

 <?php
if($_POST['submit']){

// 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
	if(is_array($errors))
	{
		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 />';
		}echo'</ul></div>';
	}
	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" />
    Website:
    <input class="element" name="website" type="text" value="http://" />
    <input name="submit" type="submit" />
  </form>

demodownload



More tutorials from Papermashup
  • http://mikeutter.com Mike

    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!

  • http://mobiland.az AzeriFire

    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)
    http://paste.org/5753

    New style with my function:
    http://paste.org/5754

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

  • http://mobiland.az AzeriFire

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

  • http://www.papermashup.com Ashley

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

  • http://mobiland.az AzeriFire

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

  • http://www.papermashup.com Ashley

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

  • http://mobiland.az AzeriFire

    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: http://paste.org/5736