Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
10.7%
PHP


by Subhash Vithanapathirana

Hey all the code buddies.. How are you doing? We discussed about defining functions in PHP in the last month's article. Today we are heading towards the usage of PHP for the purpose of handing form inputs. I expect this to be an interesting topic of discussion for most of you.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />


Introduction

I am sure you must have experienced hundreds of forms while browsing the WWW. Either it is a user registration page, user sign-in page, forgot password page, contact us page, file upload page or even a order placement page you definitely will find one or more forms. When you input some values into the various form elements such as text fields, drop down menus, checkboxes and press the submit button, what actually happens to these data? If you are not yet sure, you'll find the answer soon.

Simple answer is, the data you enter will be transferred to the server as either GET or POST request. These are the two methods of data transferring supported by HTML forms each having their own pros and cons.


Let's see what they actually means:


l  GET method sends the data in the URL string. The length of data which can be sent through this method is limited and it is browser specific. It is very much suitable for displaying purposes such as searching, sorting and pagination.


l  POST method sends data to the server invisible to the user and considered safe way compared to the above. There is no limit of data to be sent and useful when working with user inputs which ends up in a database.


 The form page


 The HTML form tag has several attributes which can be of interest to us in this topic. Look at the following tag:


<form name="myForm" method="GET" action="handle.php">


 


1.    name: attribute used to identify a specific form uniquely in the HTML page. You may not feel the importance of it in this example but it is always good to define one.


2.    method: attribute to set the data transfer method which was described earlier. The value can be either GET or POST.


3.    action: attribute to set the server-side script page name/path which handles the form submission. In this example it is handle.php.


 Let's construct a complete HTML page including a form so you will understand things more clear.


<html>


 <head>


 <title>My first form</title>


 </head>


 <body>


 <form name="myForm" method="GET" action="handle.php">


 Name: <input type="text" name="txtName" value="" /><br />


 Age: <input type="text" name="txtAge" value="" /><br />


 <input type="submit" name="btnSubmit" value="Submit" />


 </form>


 </body>


 </html>


 Save the above piece of HTML as form.html (or any name you like) under you Web root folder. Take a look at the output by typing http://localhost/form.html in browser. You will see a simple page with two text fields to enter name and age with a button to submit the form.


 


The form handler script


 Having the form page in place, next we need to code our form handling script. This is where we capture the user input in previous page and do whatever the processing that is required.


<?php
$myName 
$_GET["txtName"];
$myAge $_GET["txtAge"];

echo "Hi " $myName "! Are you " $myAge " years old?";
?>


Something similar to above can be in your handle.php. You will notice if you enter some values in to the text fields of form.html and press submit button, you will be directed to following URL.


http://localhost/handle.php?txtName=John&txtAge=25&btnSubmit=Submit


$_GET is an associative array which contains the values passed into the current page via the URL of the page. The keys of the array are the name of the variables (text box names in this case) and value is simply the data you entered in them.


What if you use the method="POST" in form.html? You hit the submit button with values in text boxes, the difference is you will not able to see the values appending to the URL.


http://localhost/handle.php


Yes, it is very much secure than previous method since no one can mess with the values on it's way to the server (let's call it less hackable!). The changes you need to perform in handle.php is you need to use $_POST[] associative array instead of $_GET[]. You'll be able to see the exact same output in both methods in handle.php.


 


  Validating input


 I don't expect to go in depth into methods of validating data at this point. Will just show you how to simply validate whether the name input is empty and age is between a given range. Just a head start for you...


<?php
$myName 
$_POST["txtName"];
$myAge $_POST["txtAge"];

if($myName == "")
{
echo 
"<font color=\"#ff0000\">Please enter your name.</font>";
elseif(
$myAge == "" || $myAge 15 || $myAge 40)
{
echo 
"<font color=\"#ff0000\">You should be 15-40 years to view this page!</font>";
} else {
echo 
"Hi " $myName "! Are you " $myAge years old?";
}
?>


Try this as your handle.php. I have used $_POST[] in this example. Of course, you can write more comprehensive validations here such as to check whether data are of expected type, format, length etc. It depends on your requirements.


This is one way of handling and validating the form by directing user to a separate page such as handle.php in this case. It is the simplest and “traditional” way of doing it. But often we see in websites that the errors are displayed on top of the form you filled, in the same page itself. How can this be done? Obviously you will have to set the form's action attribute to the same page as you're in. For that, your form too should be placed in a PHP page (not in a HTML page such as form.html). Let's rename it to form.php for this purpose.


Then your form tag should read:


<form name="myForm" method="POST" action="form.php">


 One issue with hard-coding the filename is that if you accidentally rename the filename of this page to form123.php one day and forget to make a change to action attribute, it will end up in 404 page once you submit the form. To minimize the chances of such a mistake, will use the following:


<form name="myForm" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">


 This way the PHP identifies the current page's filename and embeds it into the action attribute. (see the page source from your browser to see the filename printed) Smart! ;-)


http://localhost/form.php


Browse the above location using your browser to see the form. When you hit submit you'll see that the form is posted to same page as you are currently in. I will leave the rest of the code of validating and processing part for you... Basically you need to find out a mechanism to trigger the validation and form handling logic only when form is submitted, but NOT in the first time load of the page (when user sees the form). I assume this can be a good exercise for you to get into the terms of “professional” way of handling a form.


If you get stuck on the process, or even if you succeed with it, please feel free to mail me with your scripts on codekadiya at gmail dot com. Enjoy! :-)


Previous Article

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options