Tuesday, May 21, 2013

0 Comments
Posted in Arrangement, Art, Business

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


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.
  1. <form id="commentform" method="post" action="errorpart2.php">  
  2.     <p>  
  3.     <label for="name">Name:</label>  
  4.     <br/>  
  5.     <input name="name" id="name" type="text"/>  
  6.     </p>  
  7.     <p>  
  8.     <label for="email">Email:</label> <br/>  
  9.     <input name="email" id="email" type="text"/>  
  10.     </p>  
  11.     <p>  
  12.     <label for="comments">Comment:</label>  
  13.     <br/>  
  14.     <textarea name="comments" id="comments" rows="4"></textarea>  
  15.     </p>  
  16.     <p>  
  17.     <input name="submit" id="submit" type="submit" value="Submit" />  
  18.     </p>  
  19. </form>  
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.
  1. if (array_key_exists('submit',$_POST)){  
  2. //Form has been submitted  
  3. }  
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.
  1.     // Fields that are on form  
  2.     $expected = array('name''email''comments');  
  3.     // Set required fields  
  4.     $required = array('name''comments');  
  5.     // Initialize array for errors  
  6.     $errors = array();  
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.
  1. foreach ($_POST as $field => $value){  
  2.     // Make sure field was done correctly otherwise add error.  
  3. }  
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:
  1. // Assign to $temp and trim spaces if not array  
  2. $temp = is_array($value) ? $value : trim($value);  
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:
  1. // If field is empty and required, tag onto $errors array  
  2. if (empty($temp) && in_array($field, $required)) {  
  3.       array_push($errors, $field);  
  4.   
  5. }  
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:
  1. if (empty($errors)){  
  2.         //The form is completed properly to do with as you please  
  3.         unset($errors);  
  4. }  
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:
  1. <?php if (isset($errors) && in_array('name'$errors)){?>  
  2. <div class="red">Please enter name</div>  
  3. <?php } ?>  
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 &quot; ).
  1. <input name="name" id="name" type="text"  
  2.     <?php if (isset($errors)) { echo 'value="'.htmlentities($_POST['name']).'"'; } ?>  
  3. />  
The above will work for inputs, but the following tweak must be done to accommodate a textarea:
  1. <textarea name="comments" id="comments" rows="4"><?php  
  2.     if (isset($errors)) { echo htmlentities($_POST['comments']); }  
  3. ?></textarea>  
It is important to note that in order to avoid white space, make the <?php tags touch the textarea tags.
0 Comments
Posted in Arrangement, Art, Business

How to Validate a Form Using PHP Part 1: Complete with Error Messages!


How to Validate a Form Using PHP Part 1: Complete with Error Messages!

Having a site visitor fill out a form is the primary way to gather information. Forms are the main line of communication with anyone that visits your site, so taking the time to make sure users fill them out correctly is key. Using PHP, we are able to ensure that all fields are properly filled out before submission, with required adjustments being called to attention through the use of error messages.

The CSS & HTML Groundwork

Let’s start off by opening up a fresh php document and putting a form within it. I have created errorpart1.php
  1. <html>  
  2.     <head>  
  3.         <title>Form validation using PHP</title>  
  4.         <style type="text/css"><!--Styles--></style>  
  5.     </head>  
  6.     <body>  
  7.         <div id="content">  
  8.            <!--PHP and Form to go here-->  
  9.         </div>  
  10.     </body>  
  11. </html>  
With the following styles applied to the form:
  1. *{  
  2.     padding:0px;  
  3.     margin:0px;  
  4. }  
  5. body{  
  6.     text-align:center;  
  7.     font:11px "Lucida Grande",Arial,sans-serif;  
  8. }  
  9. #content{  
  10.     width:300px;  
  11.     text-align:left;  
  12.     margin:10px;  
  13. }  
  14. .formitem{  
  15.     width:100%;  
  16.     padding6px;  
  17.     font:11px "Lucida Grande",Arial,sans-serif;  
  18. }  
  19. h2{  
  20.     font:18px "Helvetica",Arial,sans-serif;  
  21. }  
  22. .box{  
  23.     width:100%;  
  24.     padding:10px 0px 10px 5px;  
  25.     margin-bottom8px;  
  26.     font-weight:bold;  
  27. }  
  28. .green{  
  29.     background-color:#95ca78;  
  30.     border-bottom:solid 1px #8AA000;  
  31. }  
  32. .red{  
  33.     background-color:#FDCBCA;  
  34.     border-bottom:solid 1px #E8514A;  
  35. }  
Next we have to construct our form, I have chosen to create a three field form, including one hidden field entitled “submitted”, which serves to check if the form has been completed.
  1. <form action="index.php" method="POST" enctype="multipart/form-data">  
  2.     <h2>Title</h2>  
  3.     <input class="formitem" type="text" name="title"/>  
  4.     <br/><br/>  
  5.     <h2>Content</h2>  
  6.     <textarea class="formitem" name ="textentry" rows="3"></textarea>  
  7.     <input type="hidden" name="submitted" value="1">  
  8.     <br/><br/>  
  9.     <input type="submit" value="Submit"/>  
  10. </form>  
Now that we’ve laid out and styled up our page, it’s time to come in with some PHP.

The PHP and Validation

First we’ll use the hidden field (“submitted”) that we created earlier to check if the form is ready to be validated aka if they submitted it. We can do this with a simple IF statement, checking to see if submitted has a value of “1″, which it it automatically set to on form submission. This prevents error messages from popping up unless the form was actually completed and turned in.
  1. <?php  
  2. //If form was submitted  
  3. if ($_POST['submitted']==1) {  
  4.    //Do something  
  5. }  
  6. ?>  
Next up we have to check each mandatory field for a value of some kind. I have decided that both the title and content fields are mandatory for this example. The below code checks for values in each field on the form and assigns them to a variable if they exist.
  1. <?php  
  2. //If form was submitted  
  3. if ($_POST['submitted']==1) {  
  4.     if ($_POST[title]){  
  5.         $title = $_POST[title]; //If title was entered  
  6.     }  
  7.     if ($_POST[textentry]){  
  8.         $textentry = $_POST[textentry]; //If comment was entered  
  9.     }  
  10. }  
Now that we have put the values retrieved from the form into variables, we can perform a check to see if any are blank. If they have all been filled out properly, a message alerts them they completed the form properly.
  1. //If all fields present  
  2. if ($title && $textentry){  
  3.     //Do something  
  4.     echo "<div class=\"box green\">Form completed!</div>";  
  5. }  
  6. ?>  
Now for those of you that are currently questioning why I didn’t combine the last two parts into one big IF statement, hold on, it’s error message time.

At this point in the game, we want to go back to where we first assigned the $_POST variables to strings variables, appending an else to each IF statement.
  1. if ($_POST['submitted']==1) {  
  2.     $errormsg = ""//Initialize errors  
  3.     if ($_POST[title]){  
  4.         $title = $_POST[title]; //If title was entered  
  5.     }  
  6.     else{  
  7.         $errormsg = "Please enter title";  
  8.     }  
  9.     if ($_POST[textentry]){  
  10.         $textentry = $_POST[textentry]; //If comment was entered  
  11.     }  
  12.     else{  
  13.         if ($errormsg){ //If there is already an error, add next error  
  14.             $errormsg = $errormsg . " & content";  
  15.         }else{  
  16.             $errormsg = "Please enter content";  
  17.         }  
  18.     }  
  19. }  
That last section might have seemed like a lot, so let’s break it down.
First off we established the variable $errormsg, which will contain a string with all the errors we come across.
  1. $errormsg = ""//Initialize errors  
Next we append the first IF statement for the title field, stating that if there is no value, set the $errormsg to store that error.
  1. else{  
  2.     $errormsg = "Please enter title";  
  3. }  
When we check the next field, textentry, we will essentially be doing the same thing, although this time we must check if $errormsg has any errors stored from the previous IF. Should this be the case, we must append our current error message to the previous one.
  1. else{  
  2.     if ($errormsg){ //If there is already an error, add next error  
  3.          $errormsg = $errormsg . " & content";  
  4.     }else{  
  5.          $errormsg = "Please enter content";  
  6.     }  
  7. }  
At this point your $errormsg variable should have an accurate list of error messages stored. Now it is time to alert the user of any problems.
  1. if ($errormsg){ //If any errors display them  
  2.     echo "<div class=\"box red\">$errormsg</div>";  
  3. }  

    Blogger news

    Blogroll

    About