Jump to content


Looking for Good Example of Form Validation

  • Please log in to reply
5 replies to this topic

#1 HenryCan


    Advanced Member

  • Members
  • PipPipPip
  • 42 posts

Posted 16 January 2013 - 03:56 PM

I'm trying to track down one or more good examples that show a form being presented, validated and then handled, preferably all on the same page.

I'm new to PHP but I've been coding in various other languages for many years so I'm definitely not new to programming. I googled on "php form handling" and found this article:

I've never validated a form in PHP but I like the idea of displaying, validating and then handling the validation of the form on the same page. But I'm open to arguments that this is not the best way to proceed. My big problem is that the article provides only snippets from an actual solution, not a full script. Since I'm new at PHP, I don't have the experience to imagine all the stuff that he has omitted. I've also discovered in subsequent searching that the author's approach is prone to injection attacks and I certainly want to avoid that.

Therefore, I would love to find some COMPLETE examples that show all displaying, validating and handling of the data in the form. The example should use the techniques that best avoid injection attacks.

For what it's worth, my form will prompt the user for some information about proposed meeting topics for a book discussion club, and validate to make sure the user has completed the form correctly. If the user has made errors, I'd like to display the errors to him on the same page as the form so that he can make the appropriate changes and then resubmit. Once the data checks out as vaild, I will insert a row to a table in a MySQL database.

I'm fluent with HTML and database so displaying the form and inserting the row into the database table are well within my grasp. I don't need any major amount of instruction there. But the proper techniques to validate the data and display errors on the same page as the form is something I've never done in PHP. (I have done it in Java servlets running in Tomcat and in mainframe applications but the techniques seem rather different for PHP.)

#2 kicken


    Wiser? Not exactly.

  • Gurus
  • 2,702 posts
  • LocationBonita, FL

Posted 16 January 2013 - 10:58 PM

The way I handle forms basically boils down to something like this:

$Defaults = array();
$Errors = array();

if (count($_POST) > 0){
   $Defaults = $_POST;
   //validation stuff
   if (count($Errors) == 0){

if (empty($Defaults)){
   //Load defaults from DB if necessary

//Show form

Within the template file for the form I use the $Defaults and $Errors variables to pre-fill form fields and display any error messages.  A more complete example would be like this (a simple contact form).


$Defaults = array();
$Errors = array();

if (count($_POST) > 0){
    $Defaults = $_POST;

    if (empty($_POST['contactName']) || strlen(trim($_POST['contactName']))==0){
        $Errors[] = 'Name is a required field.';

    if (empty($_POST['contactEmail']) || !filter_var($_POST['contactEmail'])){
        $Errors[] = 'Email is a required field.';

    if (empty($_POST['message']) || strlen(trim($_POST['message'])) == 0){
        $Errors[] = 'Message is a required field.';

    if (count($Errors)==0){
        $message = "
You have receive a contact request from {$_POST['contactName']} ({$_POST['contactEmail']}).  The message left was:

        if (!mail("myemail@example.com", "Contact Request", $msg)){
            $Errors[] = 'Unable to send your message.  Please try again later.';
        else {



<!DOCTYPE html>
  <title>Contact me</title>
  <form method="post" action="contact.php">
   <?php if (!empty($Errors)): ?>
      <?php foreach ($Errors as $err): ?>
      <?php endforeach; ?>
   <?php endif; ?>

   <p>Name: <input type="text" name="contactName" value="<?=htmlentities($Defaults['contactName']);?>"></p>
   <p>Email: <input type="text" name="contactEmail" value="<?=htmlentities($Defaults['contactEmail']);?>"></p>
   <p>Message:<br><textarea name="message" rows="10" cols="60"><?=htmlentities($Defaults['message'])?>"><textarea></p>
   <p><input type="submit" value="Send Message"></p>

I just whipped that up in a few minutes here.  As is it will show some E_NOTICE errors for undefined indexes, didn't test at all so may not even function right.  It should demonstrate fairly well though.  I have a template system I use in my production stuff that normally would handle preventing the E_NOTICE errors.  One could wrap up some of the validation stuff into a library to make it a little less tedious also. 
Recycle your old CD's, don't trash them!
Did I help you out?  Feeling generous? I accept tips via Paypal or Bitcoin @ 14mDxaob8Jgdg52scDbvf3uaeR61tB2yC7

#3 HenryCan


    Advanced Member

  • Members
  • PipPipPip
  • 42 posts

Posted 17 January 2013 - 09:01 AM

Thanks for the example, kicken. There are a few things that aren't obvious to me from your example.

1. What is an "E_NOTICE"? You refer to them after the example but I don't see any variables with that name so I'm not sure what you mean.
2. What is the significance of the .tpl file extension on the last file? I've never seen that one before. I'm guessing it is short for "template" but I'm not sure what the effect is of executing code with a .tpl extension is in a PHP environment.
3. Is this approach safe from injection attacks? How would it have to change to be safe?

#4 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 17 January 2013 - 10:54 AM

  • E_NOTICE is the error-level constant for notices, which is defined by PHP itself.
  • The significance is only what you give it. Most people tend to give their files some meaningful endings for humans, in this case it's telling us that the file in question is a template file.
    As long as you include it, and it contains proper PHP code + tags, PHP doesn't care what it's named. Apache might care, but only so far that you have to tell it to parse it as a PHP file.
  • Yes, the code he posted is safe against injection attacks. That's why he used htmlspecialchars () in the template file.
    The e-mail message itself cannot be attacked in that manner, as it's pure text. The only thing an attacker might be able to do, is to end the message prematurely and thus cause the rest of the content to be silently dropped by the MTA.
    No e-mail headers are generated based upon the user-input either, so that's going going to be a concern.

Edited by Christian F., 17 January 2013 - 10:55 AM.

Keeping it simple.

#5 White_Lily


    Advanced Member

  • Members
  • PipPipPip
  • 521 posts

Posted 22 January 2013 - 06:04 AM

Although this makes things more difficult and a lot more learning for you, I think most forms should have client AND server side validation. (client side being jQuery & aJax, server-side being PHP), client side is useful so that your users dont have to waste time refilling the form out because theyve got a wrong input, jQuery and aJax validate their inputs as they are typing/clicking.

"In order to be irreplaceable, one needs to be different from another."

CMS Development: http://cms.janedeaslart.co.uk/

#6 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 22 January 2013 - 06:14 AM

You don't need to use client-side validation to save the user from having to input all of the data anew. Kicken has already covered that in his example. The only thing client-side validation saves, is a HTTP request.
Keeping it simple.

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime