Jump to content

Looking for Good Example of Form Validation


HenryCan

Recommended Posts

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:

http://onlamp.com/pub/a/php/2004/08/26/phpformhandling.html

 

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.)

Link to comment
Share on other sites

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){
      //process
   }
}

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).

 

contact.php

<?php

$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:
----------------------------------------------
{$_POST['message']}
----------------------------------------------
       ";

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

include('contact.tpl');

?>

 

contact.tpl

<!DOCTYPE html>
<html>
 <head>
  <title>Contact me</title>
 </head>
 <body>
  <form method="post" action="contact.php">
   <?php if (!empty($Errors)): ?>
   <ul>
      <?php foreach ($Errors as $err): ?>
      <li><?=$err?></li>
      <?php endforeach; ?>
   </ul>
   <?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>
  </form>
 </body>
</html>

 

 

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. 

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

  1. E_NOTICE is the error-level constant for notices, which is defined by PHP itself.
  2. 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.
  3. 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.
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.