How to Validate a Form Using PHP Part 2: Streamline Using Arrays

We’ve touched upon the basic elements of form validation and error messages in part 1 of this series, which outlines a relatively static method identifying errors and validating a form. In this edition we are going to make the elements we began with more dynamic and reduce the amount of script required to do so using arrays.

Setting Up the Form

First we’re going to want to create a form on a new .php document, mine is going to be called errorpart2.php. Below is my form complete with fields name, email, and comments.

The next step is to put in place a check to see if the form is submitted, so the script knows to validate. For those that have read part 1 of this series I had used a hidden input to pass this check, I have since done some additional research on the matter and found an alternative more secure method.

This method checks the $_POST array for the key ‘submit’, which is the array key for our Submit button, and would only be present if the form was submitted. We will be placing all of our validation related script within this IF statement, ensuring it only runs when required.

Laying Down Array Groundwork

We will need to define the arrays we will be using for this script, one containing all the field names on the form, one with all the mandatory fields, and one to store any errors we come across.

The $expected array serves to identify and process all  fields, mandatory or not. It also ensures that only the fields you specify are processed and prevents security issues from rogue $_POST values.


Making It Dynamic

The next part is where a big benefit of using arrays comes into play. Instead of typing out IF statements for each $_POST field, we can make use of the foreach statement to do this dynamically.

This snippet goes through each key and the corresponding value that the $_POST array holds. This means that each field submitted will be processed, which is especially useful when dealing with long forms.

From within this foreach we now want to do two things to each variable passed through it..
1. Clean up the variable by eliminating whitespace if it is not an array. I used shorthand for this conditional statement:

2. If field is empty then make sure it is not required, otherwise add related error message to the $error array. For those unfamiliar with array_push, it can be used to append additional values into an existing array, in this case the one we defined before:

Once these two steps are in place, we have finished the foreach statement.

Handling the Errors

Now that we have the $error array with the names of each required field not filled out, we need to either accept the form or show the error messages.

If the form is done correctly:

The unset(); function destroys the $errors array, so it does not cause incorrect error messages to be displayed.

To display error messages I placed the following lines of code next to the corresponding labels, only appearing when applicable:

This checks the $errors array for the specified field name , in this case ‘name’, which would only be present if an error happened. The same lines must be placed next to each field you are displaying an error for. I included the error message with my CSS styles applied, they can be found in the complete script at the bottom of this page.

Prevent Inputs from Clearing After an Error

When a user submits the form after completing some of the mandatory fields but not all, they would currently be shown an error message and the form would be cleared. This is a frustrating usability problem that can drive users away. Luckily, now that we have implemented array based validation, it is also easy to fix.

This line of code checks if there are any errors and, if there are, it inserts value = “” containing the user input submitted. This puts the value of the input to whatever the user had it as prior to the error, so they don’t have to retype anything. It is important to enclose this echo statement in literal ‘ ‘ quotes as well as wrap the $_POST[] in htmlentities. To ensure quotes and other symbols inputted do not break your page htmlentities converts some symbols to their HTML equivalent (example:  ” to " ).

The above will work for inputs, but the following tweak must be done to accommodate a textarea:

It is important to note that in order to avoid white space, make the <?php tags touch the textarea tags.

Completed Tutorial

And that’s all there is to it. Brace yourself for part 3, coming soon, which will outline how to check formats such as email addresses and phone numbers.

Posted Thursday, December 11th, 2008 · Back to Top

SPONSOR

Add Comment

60 Comments 3 Mentions

  1. rania Author Editor

    nice ..more user friendly ..
    uhm ..if the form is completed ..and i want to link it to another page thus submitting the data to database instead of displaying the green box ..how?

    ·

  2. Sam Dunn Author Editor

    @rania
    Assuming you have a mysql connection open and database created already you could put the following right above the green box code:
    $sql= “INSERT INTO entry (name, email, comments) VALUES (‘$_POST[name]‘, ‘$_POST[email]‘, ‘$_POST[comments]‘)”;
    mysql_query($sql) or die(‘Error: ‘ . mysql_error());

    Please let me know if that answers your question

    Thanks, Sam

    ·

  3. rania Author Editor

    im trying wth d code ..another thg ..when will part 3 will be posted?

    ·

  4. rania Author Editor

    the code is for submitting details to database ..what if i when user click submit and all details are filled. i want to link it to another page

    ·

  5. rania Author Editor

    do i replace this part ..
    if (empty($errors)){?>
    Thanks for the submission

    $sql= “INSERT INTO entry (name, email, comments) VALUES (’$_POST[name]‘, ‘$_POST[email]‘, ‘$_POST[comments]‘)”;
    mysql_query($sql) or die(’Error: ‘ . mysql_error());
    <?php
    unset($errors);
    }

    ·

  6. rania Author Editor

    with this code? ..
    if (empty($errors)){?>
    $sql= “INSERT INTO entry (name, email, comments) VALUES (’$_POST[name]‘, ‘$_POST[email]‘, ‘$_POST[comments]‘)”;
    mysql_query($sql) or die(’Error: ‘ . mysql_error());
    <?php
    unset($errors);
    }

    ·

  7. Christopher Hill Author Editor

    The idea behind this is okay, but the implementation is… lacking.

    #1 if (array_key_exists(‘submit’,$_POST)){
    Big no-no. Under certain circumstances the submit button will not be submitted on IE6. Even if it did, array_key_exists() is the wrong function; you want isset().

    What you really want to do is
    if ($_SERVER['REQUEST_METHOD'] == ‘POST’) {

    #2 Not sure why you are using array_push($errors, $field); Using language constructs is far quicker for PHP so just do:
    $errors[] = $field;

    #3 You should really be giving htmlentities() a quote style and a charset, otherwise you can be susceptible to encoding attacks.

    #4 on your reply on December 11th, 2008 at 9:13 pm, your SQL query is not protected against SQL injection.

    Just a heads up.

    ·

  8. Matthew Knight Author Editor

    Further to Christopher Hill’s points, instead of using

    if ($_SERVER['REQUEST_METHOD'] == ‘POST’) {

    you can do it by including a hidden input in the form – useful if you want to have multiple forms on the same page for instance.

    Our framework uses a similar system to above, but we have a function wrapper to produce all the inputs (text, textarea, checkbox, radio, password, as well as some custom ones such as date, date-time, etc). The advantage of this system is that you don’t need to have lots of logic blocks down your page checking for errors, including existing content, etc – instead it’s all contained within the function and each call might read something like:

    This might, for argument’s sake, produce code such as:

    Please enter your address:
    My Address

    and also include any error messages, existing data, etc. Obviously that’s a simplified example, but you get the general idea…

    ·

  9. Matthew Knight Author Editor

    It’s wiped all my code….

    PHP:
    echo genInput(“textarea”,”Address”,”Please enter your address:”,$existingAddressFromDatabase,array(10,40));

    HTML: (swap {} for normal angle brackets)

    {label for=”Address”}Please enter your address:{/label}
    {textarea rows=”10″ cols=”40″ name=”Address” id=”Address”}My Address{/textarea}

    ·

  10. Sam Dunn Author Editor

    @rania
    I would encourage you to look into the header(); function of PHP

    @Christopher Hill
    #1 isset() will return false for arrays keys that have their value set to NULL, which can be inaccurate, while array_key_exists would return true. I would be interested to see some information regarding the IE6 problems, as I have never come across any. Also, thank you for the alternative.

    #2 You caught me, this is a stripped down version of my validation script that makes use of array_push, which seems to have slipped through the cracks, I’ll have to make that adjustment thank you.

    #3 For this script, the default quote style and charset both work for what I’m trying to do, ISO ISO-8859-1 and ENT_COMPAT.

    #4 @rania too, the purpose of that post was to show where a potential SQL query could go, nothing else. It is not secure and you should apply your own methods of protection to make it so.

    I plan on making a part to this series regarding form security, this tutorial was just laying down the groundwork for doing so.

    @Matthew Knight
    In part one of this series I made use of the hidden input on the form, but due to some very opinionated comments I decided to show an alternate method this time around.

    Your form generation technique is very interesting and is something I plan on exploring, thanks for showing me.

    ·

  11. Christopher Hill Author Editor

    @Sam Dunn
    #1 I’m not sure why a submit button would have a value of NULL, though. And feel free to test out the IE6 bug out on my test page: http://www.chrisjhill.co.uk/lab/ie6_no_submit_button/

    ·

  12. Sam Dunn Author Editor

    @Christopher Hill
    Thanks for that, interesting bug. I’ll take that into account for 1 input forms.

    ·

  13. Matt Author Editor

    I think this way of error processing is nice, but can you show me why your code is more sufficient than this:

    function print_errors($e)
    {
    // print out the errors in an un-ordered list.
    ?>
    Errors

    Sorry, an error has occured. This could be due to lack of required input, or a typo.
    The error(s) returned:

    <?php echo implode(”, $e);?>

    <?php
    }

    // if there were any errors with processing
    if( $_errors )
    {
    // print the errors
    print_errors($_errors);
    }

    if ($field['name'] == “NULL”) $errors[] = “missed some data”;

    Is your way more efficient, and does it have more flexibility?
    If so then I’m switching to your way, so write back.

    ·

  14. Sam Dunn Author Editor

    @Matt
    There are a few benefits of the way I outline above, that I don’t see offhand built into your way.
    1. The ability to specify mandatory fields versus optional.
    2. Because my method stores errors in an array by field name, rather than error message, you would be able to keep user input from clearing upon an error. You would also be able to display errors beside the related field.
    3. Your print_errors array seems like an redundant function, you don’t need a function to display errors onscreen.

    ·

  15. Darin Boyd / Braingerous Author Editor

    I like your site. You’ve done a good job of showing a basic validation technique for a web form. Your presentation looked very nice also.

    Validation is notoriously cumbersome. It is also a fairly repetitive task. These are scenarios where objects designed to handle these tasks would reduce a lot of the boiler plate work and separate those concerns from the form code.

    I come from a .Net background where we have frameworks like Enterprise Library and CSLA. I’m doing some PHP these days, so I still haven’t gotten to grips with best practices in the community. I began coding my own validation framework as a discussion on my blog, but recently also discovered a framework called Kohana. Have you tried anything like that?

    ·

  16. Zac Author Editor

    One problem I found with this validation process is that is doesn’t handle check boxes or radio buttons very well. Check box and radio button values are only added to the $_POST array when checked/selected. So, the foreach statement around line 64 will ignore required check boxes/radio buttons if they aren’t checked.

    ·

  17. Adham Author Editor

    nice tutorial
    but what is the benefit of the following :-
    $temp = is_array($value) ? $value : trim($value);
    the question is can $value be an array ?
    $value have to be posted by the user how can it be an array ?

    ·

  18. MikeW Author Editor

    I’m totally new to php so all this conversation is very interesting. However, I have a very basic question (I think). When I use your technique of validation:

    <input name=”name” id=”name” type=”text”

    />

    the Expressions Web tool tells me that in XHTML 1.0 Strict the attribute above is not permitted for the tag. I’ve been unable to get the technique to work. I must be making a rookie mistake. Does the technique have to use imbedded php or can the checking be done in an external .php file?

    ·

  19. JacksonL Author Editor

    Hi,
    I’m also fairly new to PHP, I’ve been searching around the internet for a tutorial exactly like this. Can i personally thank you, as this has helped me out alot. But i have two questions, one is how would i send this data in a email to myself? And second, instead of Thanks for the submission is their a way to make it go to a thankyou page?

    Thanks,
    Jackson – New Zealand

    ·

  20. Sam Parkinson Author Editor

    Thanks man, I was having a few problems returning errors to the users and keeping the form data. Problem solved now, although I didn’t use that loop, not the most secure way of checking a forms validity (admittedly its a lots less typing that an if statement for each form input though :P).

    ·

  21. Chris Benton Author Editor

    This is a great script. Helped me out immensely. Is it possible to modify it to cover checkboxes, lists, and radio buttons? I have a checkbox field listed in my “required” array, but the script doesn’t seem to notice it.

    ·

  22. kofi peprah Author Editor

    I’m still working around my website when it is published i’ll let you know.

    Your code has really helped me, thanks so much. I have therefore decided to create a link to this site on my mine.

    ·

  23. Chris Author Editor

    How would this work with check boxes and lists?

    ·

  24. Jore Author Editor

    Hi…
    I really liked this application… but, how do i have to do to select values from a “dropdown form” and validate them aswell?

    thanks!

    ·

  25. Vladimir Author Editor

    Super.. Nice.. Very nice scripts.. Thanks :) This site the best! Agian thanks.

    ·

  26. Vladimir Author Editor

    Please add capcha with image or text from bots.. thanks :)
    or help from how add the capcha for this script :)
    My email you see.

    ·

  27. Sinan Author Editor

    @Adham

    Because you can, like this:

    then when the form is submitted, $_POST['options'] will be already an array ;) . Let the fun begin

    ·

  28. Sinan Author Editor

    OPS ! my code is gone :)
    @Adham

    Because you can, like this:

    input name=”options[]” type=”text”

    then when the form is submitted, $_POST['options'] will be already an array ;) . Let the fun begin

    ·

  29. Lionel okeke Author Editor

    hi you guys lovely tutorials but i need you help on validating radio butttons with php and send the values to mysql database, that would be lovely, thanks you guyz

    ·

  30. Greg Author Editor

    That <> is better than <> is undoubtedly. You should change the script accordingly.
    What I do not understand is why <>? This really makes no sense at all. What it bothers me is that it makes no sense even if the posted value is indeed an array.

    I understand that it’s beyond the purpose of this tutorial the problem of multiple selection as in the case of “checkboxes” or (some) “select” fields. For example this one:
    I know PHP
    I know JavaScript

    Now if you want to use an array you can write something like this:

    I know PHP
    I know JavaScript

    Now the fun begins as you may want to check both:
    $_POST['programminglanguages'][0] and
    $_POST['programminglanguages'][1].

    At this point the $_POST['programminglanguages'] is indeed an array, but your code mentioned above makes no sense.

    Nevertheless, a good starting point. Congrats.

    ·

  31. Greg Author Editor

    That < > is better than < > is undoubtedly. You should change the script accordingly.
    What I do not understand is why < > ? This really makes no sense at all. What it bothers me is that it makes no sense even if the posted value is indeed an array.

    I understand that it’s beyond the purpose of this tutorial the problem of multiple selection as in the case of “checkboxes” or (some) “select” fields. For example this one:
    I know PHP
    I know JavaScript

    Now if you want to use an array you can write something like this:

    I know PHP
    I know JavaScript

    Now the fun begins as you may want to check both:
    $_POST['programminglanguages'][0] and
    $_POST['programminglanguages'][1].

    At this point the $_POST['programminglanguages'] is indeed an array, but your code mentioned above makes no sense.

    Nevertheless, a good starting point. Congrats.

    ·

  32. Greg Author Editor

    That $errors[] = $field; is better than array_push($errors, $field); is undoubtedly. You should change the script accordingly.
    What I do not understand is why $temp = is_array($value) ? $value : trim($value); ? This really makes no sense at all. What it bothers me is that it makes no sense even if the posted value is indeed an array.

    I understand that it’s beyond the purpose of this tutorial the problem of multiple selection as in the case of “checkboxes” or (some) “select” fields. For example this one:
    I know PHP
    I know JavaScript

    Now if you want to use an array you can write something like this:

    I know PHP
    I know JavaScript

    Now the fun begins as you may want to check both:
    $_POST['programminglanguages'][0] and
    $_POST['programminglanguages'][1].

    At this point the $_POST['programminglanguages'] is indeed an array, but your code mentioned above makes no sense.

    Nevertheless, a good starting point. Congrats.

    ·

  33. Greg Author Editor

    I am sorry, but your blog handles very bad meta characters and tags. i hope you can delete the posts and edit the code accordingly. It is pretty funny especially that you advise using htmlentities, but you’re not using it yourself, at least not here. :P

    ·

  34. Dev Author Editor

    Great tutorials.

    Have you guys posted part 3 yet? I can’t seem to find it. Quite looking forward to learning from it.

    Many thanks
    Dev.

    ·

  35. James Author Editor

    Hi,

    How would you Validate a select box using PHP and also what about XSS and SQL injection attacks, shouldn’t you also use Regular expressions ?

    Thanks

    ·

  36. Devin Author Editor

    Script worked out perfectly for me. Thanks for this.

    ·

  37. Jon Kristian Author Editor

    Elegant and easy to adapt, great walkthrough.

    ·

  38. rupesh raut Author Editor

    really it’s more helpful

    ·

  39. Pankti Author Editor

    umm.. Sam Dunn… Sir.. awesome webpages.. i am designing a mail client using PHP.. can u help me out wid dat? plese plese ples?! Tx….! :))

    ·

  40. aryaan Author Editor

    i get the the following error any idea?

    Warning: array_push() expects parameter 1 to be array, null given in C:\wamp\www\phppractise\new2.php on line 12

    ·

  41. aryaan Author Editor

    sorry this my code: and i get this error :Warning: array_push() expects parameter 1 to be array, null given in C:\wamp\www\phppractise\new2.php on line 12

    $value){
    $temp = is_array($value) ? $value : trim($value);
    if (empty($temp) && in_array($field, $required)) {
    global $listed_array;
    array_push($errors, $field, $required);

    }
    if (empty($errors)){
    //the form complet
    unset($errors);
    }
    }
    }
    ?>

    ·

  42. aryaan Author Editor

    oh yeah! sorry for the trouble no need to answer my question cause i has a curly bracket at the wrong place. thanks

    ·

  43. NameCo Author Editor

    Do you have PHP and CSS will help you guys? message recording system? thanks :-D

    ·

  44. Keith Russell Author Editor

    where is part 3??? lol

    ·

  45. Mircosx Author Editor

    I’m new to php, very nice script, works very good but… how do I post data to the db if I’m using the post button to validate the form??

    thanks in advance

    ·

  46. MattD Author Editor

    The comment by Keith Russell makes a good point… where is part 3?? Did this tutorial fall into completion limbo? After reading all the comments, it appears that 99% of the readers are fluent enough in PHP to finish the project themselves. I am not in that exclusive club. The thorough explanations Sam gives have been exceedingly helpful to me, and I would really appreciate the conclusion to his tut. Come on guys… help out a noob.

    ·

  47. khncnihdip Author Editor

    and baeing Chanel Handbags [url=http://www.onlinechanelbagsales.com/]Chanel Bags Sale[/url] have been verywell-liked right Chanel Online – http://www.onlinechanelbagsales.com/ since the time [url=http://www.onlinechanelbagsales.com/]Chanel Bags[/url] the brand [url=http://www.onlinechanelbagsales.com/]Chanel Bags[/url] launched [url=http://www.onlinechanelbagsales.com/]Chanel Bags[/url] its first range of handbags. Over the years, many celebrities from all around the world have been spotted flaunting a Chanel handbag. The colours, the designs, the textures, the materials, and just about everything that makes up a Chanel handbag speaks of style and class. Each handbag is crafted with so much of efficiency, that it speaks volumes about the brand’s dedication towards the improvement in the world of vogue.Just about any bag from the Chanel brand is a masterpiece in itself. Luckily, for those who do not have access to a Chanel store in their nearby area, there is now an online purchase option available. The authentic Chanel bags can be selected online, and can then be delivered at your doorstep, giving you the luxury princess cure of ordering things from the comfort of your own home.The official Chanel website has all its products available for you at just their lowest possible prices. This, the website explains is because, they source their bags and other items from their factories where the bulk production takes place. The stuff you buy from the brand’s own site will obviously be a hundred percent authentic Chanel. Now you do not have to worry about the originality of the branded bags you purchase from all those distributors, retailers and multi brand online stores. Some of them might be trustworthy, but it is always better to opt for the official site for any brand when it comes to online shopping.The numerous discounts, season sales and offers on Chanel bags online are all listed on the site. So take the shortcut and register online officially to Chanel.

    ·

  48. Requiem Author Editor

    Mr. Dunn, I believe you can help me with this.
    My professor gave us a problem.

    Let me express in this way: 1 text box and submit button.
    If I put 1 in text box, 1 asterisk will appear. If I put 24, 24 asterisks will appear. So it depends on the user what number he/she will put on the text box. And the asterisk/s depends on the number that the user will enter on the text box.

    Thanks! I hope you will answer my question. More power and Godbless!

    ·

  49. Arnold S. Author Editor

    Maybe you can help me with my problem: How do I get the “Prevent inputs from clearing after an error” part working if I’m not using an array, and the form code is in a .html file with the php code to validate in a seperate .php file?

    An example of one of my input statements in the .html file is:

    <input type="text" value="” name=”address2″ maxlength=”50″ size=”30″>

    ·

  50. Arnold S. Author Editor

    I noticed that the submission wiped out the part of my Value statement between the two quotes. Don’t know how to make them show up.

    ·

  51. james Author Editor

    i like this article

    ·

  52. Bhavik Author Editor

    thanks great tutorial but still confuse about which code i have to put in which file??? can you give vedio tutorial for better understand..???

    ·

  53. Yaz Author Editor

    Fantastic might mate!

    ·

  54. Faisal Author Editor

    I am new to php. This script was an enormous help, and it is brilliantly explained. I thank you sincerely for the effort.

    There is one thing I did not understand though.
    You did not declare the variable $field and $value anywhere, so I assumed they were some sort of global predefined variables, but they do not show up anywhere in php manual online or in any google search.
    Can some one explain?

    ·

  55. katpal Author Editor

    By using the htmlentities inside the html tags – the reset button does not work.

    ·

  56. bbmak0 Author Editor

    Where is the complete source I can look at. Looking piece to piece is hard to see the big picture.

    ·

  57. Fred Author Editor

    Where’s part 3? This looks like some good stuff. Thanks

    ·

  58. John Author Editor

    Hi
    I have two php forms form1 and form2. I’m using captcha in form1, if the captcha code is correct i need to post data to form2, however if i use

    the form is submitted despite of wrong captcha, please help how to prevent it.

    Thanks in advance

    ·

  59. K Author Editor

    GOOD

    ·

  60. star Author Editor

    thank you very much

    ·

 

Build Internet by One Mighty Roar. Since 2008.