Friday, June 29, 2012

Form Processing with PHP


Form Processing with PHP


PHP "superglobals"

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.
These superglobal variables are:
v  $GLOBALS
v  $_SERVER
v  $_GET
v  $_POST
v  $_FILES
v  $_COOKIE
v  $_SESSION
v  $_REQUEST
v  $_ENV

For the today’s lesson we are going to use $_SERVER, $_GET and $_POST SUPERGLOBAL arrays.

$_SERVER


$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.
Followings are some of the server variables.

'PHP_SELF'
The filename of the currently executing script, relative to the document root.

'SERVER_ADDR'
The IP address of the server under which the current script is executing.

'REQUEST_METHOD'

Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

'HTTP_HOST'

Contents of the Host: header from the current request, if there is one.



<?php
echo $_SERVER['PHP_SELF'].'<BR>';
echo $_SERVER['SERVER_ADDR'].'<BR>';
echo $_SERVER['REQUEST_METHOD'].'<BR>';
echo $_SERVER['HTTP_HOST'].'<BR>';
?>
 
 







What is Form Processing?

We use html <from> tag to create an html from. Inside an html form we can include text boxes, Combo boxes, Radio buttons, Test areas, Check boxes to represent data. To submit a form data, we use submit button.
There are two sides to form processing: the client-side and the server-side.
The client-side is the actual form that a visitor sees on your Web page. The form accepts the information entered by the user and the browser will do the form processing.
The server-side is a little more complicated, mainly because you have so many options for form processing. When the browser sends the form data to the server, it (the browser) assumes the server knows what to do with it. The server relies on you, the webmaster, to provide those instructions.
There are many ways to submit data to server using an html form.   We only consider about get and post methods.

<FORM METHOD=" " ACTION=" ">
Form tag contains two attributes. One is “Method” at the method we specify weather to use GET or POST.
“Action” attributes is the page we request from the server. That means, when user submits the form data, page we specified at the action attribute will accept and process it.

In most situations where you are using an HTML form, the POST method is preferable. It is not only better aesthetically because the submitted values are not revealed in the script URL but there is no limit on the amount of data that can be submitted in this way. The amount of data that can be submitted by using the GET method is limited by the maximum URL length that a web browser can handle (the limit in Internet Explorer is 2,048 characters) and the HTTP version on the server (HTTP/1.0 must allow at least 256 characters, whereas HTTP/1.1 must allow at least 2,048).





The <INPUT> Tag


The <INPUT> tag is used to add one of several types of form input to a web page. The type of input item is specified in the TYPE attribute, and the simplest type is a TEXT input item.
To create a TEXT input item that is suitable for entering a user's email address, you could use the following HTML:

<INPUT TYPE="TEXT" NAME="name" SIZE="30" VALUE="">

The CHECKBOX input type creates an input item that has only two possible values: on and off. Check boxes are useful for true/false values, and you could use the following HTML to create a check box with which the user could indicate whether he minds us contacting him by email:

<INPUT TYPE="CHECKBOX" NAME="may_contact" VALUE="Y" CHECKED>

In this case, the CHECKED attribute indicates that the check box should be checked automatically when the page loads.

The RADIO type is similar to a check box, but instead of a true/false value, a radio button group can contain several values, of which only one can be selected at a time.
To create a radio button group that can be used to gather the user's gender, you could use the following:

<INPUT TYPE="radio" NAME="gender" VALUE="m"> Male
<INPUT TYPE="radio" NAME="gender" VALUE="f"> Female

The final input type that you will learn about is the SUBMIT button. This is the button you click to send the contents of a form to the script specified in the form's METHOD attribute. The label on the button is specified in the VALUE attribute, so the following HTML would create a submit button labeled Send comments:

<INPUT TYPE=SUBMIT NAME="Submit" VALUE="Send comments">

The <TEXTAREA> Tag

The <TEXTAREA> tag is used to create a multiple-line text input item. In many respects, it behaves just like a TEXT type input tag, but the way it is formed in HTML is slightly different.

Because the initial value in a text area could span many lines, it is not given in a VALUE attribute. Instead, the starting value appears between a pair of tags, as follows:

<TEXTAREA ROWS=4 COLS=50 NAME="comments">
Enter your comments here
</TEXTAREA>

The <SELECT> Tag

The final form item we will look at is the <SELECT> item, correctly known as a menu but more commonly called a drop-down list.

The most common use of a menu is to prompt for a single selection from a predefined list of values. The following example builds a drop-down list of possible places that visitors may have heard about your website:

<SELECT NAME="referrer">
<OPTION VALUE="search">Internet Search Engine</OPTION>
<OPTION VALUE="tv">TV Advertisement</OPTION>
<OPTION VALUE="billboard">Billboard</OPTION>
<OPTION SELECTED VALUE="other">Other</OPTION>
</SELECT>

In this case, the SELECTED attribute makes "Other" the default selection, even though it appears at the top of the list. If no item has the SELECTED attribute, the first option in the list is selected by default.

Hidden Inputs

One other type of form input is available, and it can be used to pass values between scripts without their being visible on the web page itself.
The HIDDEN type takes NAME and VALUE attributes, as usual, but it simply acts a placeholder for that value.

The following hidden input is passed to the PHP script when the form is submitted, and $_POST["secret"] contains the value from the form:
<INPUT TYPE="HIDDEN" NAME="secret" VALUE="this is a secret">

Be aware, however, that HIDDEN attribute inputs are not secure for transmitting passwords and other sensitive data. Although they do not appear on the web page, if you view the page source, you can still see hidden values in the HTML code.

POST METHOD


<form id="form1" name="form1" method="post" action="process.php">
  <p>
    Na:me:     <input type="text" name="name" id="name" />
  </p>
  <p>Address:  <input type="text" name="address" id="address" /></p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>
This HTML code specifies that the form data will be submitted to the "process.php" web page using the POST method. The way that PHP does this is to store all the "posted" values into an associative array called "$_POST".

Accessing Form Values

Form values are made available in PHP by using some special array structures. The arrays $_GET and $_POST contain values submitted using the GET and POST methods, respectively.
Accessing the values from form items is fairly intuitive: The form item names become the element keys in $_GET or $_POST, and each value in the array is the value of the corresponding element when it was submitted.

process.php

<?php
$name=$_POST['name'];
$address=$_POST['address'];
echo "Hi $name <BR>";
echo "Your address is $address";
?>

Try the above program see the output.

If you need to see what are the values that contain at $_POST or $_GET user print_r() function to see it

<?php
echo "<PRE>";
print_r($_POST);
echo "</PRE>";
?>

GET METHOD


<form id="form1" name="form1" method="get" action="process.php">
  <p>
    Na:me:     <input type="text" name="name" id="name" />
  </p>
  <p>Address:  <input type="text" name="address" id="address" /></p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>

The get method is different in that it passes the variables along to the "process.php" web page by appending them onto the end of the URL. The URL, after clicking submit, would have this added on to the end of it:


The question mark "?" tells the browser that the following items are variables. Now that we changed the method of sending information on "order.html", we must change the "process.php" code to use the "$_GET" associative array.

Exercise:

Write a program to access the inputs sent by the form using get.

After changing the array name the script will function properly. Using the get method displays the variable information to your visitor, so be sure you are not sending password information or other sensitive items with the get method. You would not want your visitors seeing something they are not supposed to.

$_SERVER['PHP_SELF']

This variable is an alias to the URL of the current page. So, set the value of the action attribute to that value, and your form always resubmits, even if you've moved the file to a new place on the server.

if (isset($_POST['stage']) && ('process' == $_POST['stage'])) {
process_form();
} else {
print_form();
}
function print_form() {
echo <<<END
<form action="$_SERVER[PHP_SELF]" method="post">
What is your first name?
<input type="text" name="first_name">
<input type="hidden" name="stage" value="process">
<input type="submit" value="Say Hello">
</form>
END;
}
function process_form() {
echo 'Hello ' . $_POST['first_name'] . '!';
}



<?php
if(isset($_POST['status']) && ($_POST['status'] =='process'))
{
            $name=$_POST['name'];
            $address=$_POST['address'];
            echo "Hi $name <BR>";
            echo "Your address is $address";
}
else
{
?>
<form id="form1" name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
  <p>
    Name:   
    <input type="text" name="name" id="name" />
  </p>
  <p>Address
    <input type="text" name="address" id="address" />
    <input name="status" type="hidden" id="status" value="process" />
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>
<?php
}
?>


Using Form Elements with Multiple Options

When you have multiple input items with the same name, for example check boxes, you can use following logic at PHP code.

Example HTML form contents


Select the programming languages you can use<br>
<input name="language[]" type="checkbox" value="C++">
C++<br>
<input name="language[]" type="checkbox" value="Java">
Java<br>
<input name="language[]" type="checkbox" value="PHP">
PHP<br>
<input name="language[]" type="checkbox" value="ASP">
ASP<br>
<input name="language[]" type="checkbox" value="Delphi">
Delphi<br>


Example PHP code


<?php
if(isset($_POST['language']))
{
   $language = $_POST['language'];
   $n        = count($language);
   $i        = 0;

   echo "The languages you selected are \r\n" ;
   while ($i < $n)
   {
      echo "{$language[$i]} \r\n";
      $i++;
   }
   echo "</ol>";
}
?>


Exercise

Create a sample HTML form as follows.
NOTE: Suppose that you are going to process this form contents with a file called “Process.php”


To get the values of those input items at PHP code, we can use
$_POST['InputName'] syntax.
It will return the value entered by user to that particular input field as String.

Exercise

Create a PHP file called Procss.php to gather the information entered by the user through above HTML form. Display information as follows.

Sample Output

Name:             Saman

Gender:           Male

Filed:               Instructor

Areas:
     Networking
     DBMS

Validating Inputs

Any sensible site should include server-side validation of variables, because they are much harder to hack, and they will work no matter what browsers your visitors are using.

Basic input validation in PHP is done using the functions is_string( ), is_numeric( ), is_float( ), is_array( ), and is_object( ). Each of these functions take just one parameter, a variable of their namesake, and return TRue if that variable is of the appropriate type. For example, is_numeric( ) will return TRue if the variable passed to it is a number, and is_object( ) will return true if its variable is an object. There is one other function of this type that works the same way but is useless for validation, and that is is_resource( )it's mentioned here for the sake of completeness.

The three basic validation checks you should conduct on input are whether you have each of your required variables, whether they have a value assigned, and whether they are of the type you were expecting. From there, you can conduct more complicated checks, such as whether the integer values are in the range you would expect, whether the string values have enough characters, whether the arrays have enough elements, etc.

<?php
function ValidateName($name)
{
    $status=false;
            if (strlen($name) == 0) {
                        $status=true;
    }
            return $status;
}
function ValidateAddress($address)
{
            $status=false;
            if (strlen($address) == 0) {
                        $status=true;
    }
            return $status;
}
function ValidateAge($age)
{
            $status=true;
            if (isset($age))
            {
            if (is_numeric($age))
                        {
                                    $status=false;
                        }
            }         
            return $status;

}

?>
<?php
if(isset($_POST['status']) && ($_POST['status'] =='process'))
{
    $error=0;
            $process=true;
            $name=$_POST['name'];
            $address=$_POST['address'];
            $age=$_POST['age'];
            if(ValidateName($name))
            {
                        $error_name="Please Enter Name";
                        $error=1;
                       
            }
            if(ValidateAddress($address))
            {
                        $error_address="Please Enter Address";
                        $error=1;
            }
            if(ValidateAge($age))
            {
                        $error_age="Plese Enter Age";
                        $error=1;
            }
            if($error===0)
            {
                        echo "Hi $name <BR>";
                        echo "Your address is $address<BR>";
                        echo "Your age is $age";
            }
}
if($error!==0)
{
?>
<form id="form1" name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
  <p>
    Name:   
    <input type="text" name="name" id="name" value="<?php echo $name ;?>"/><?php echo $error_name; ?>
  </p>
  <p>Address
    <input type="text" name="address" id="address" value="<?php echo $address ;?>" /><?php  echo $error_address; ?>
    <input name="status" type="hidden" id="status" value="process" />
  </p>
  <p>AGE:
    <input type="text" name="age" id="age" value="<?php echo $age ;?>"/><?php echo $error_age; ?>
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>
<?php
}
?>

Server-Side Includes


When you developing a professional website, you need to reduce the amount of code, needs to apply code reusability, save time and effort you need. So to do that one you can use server-side includes. One of the examples is headers and footers in website. Basically PHP provides two ways to implement this. Those are require() and  include(). There are also other possible ways. 

Demonstrate the require( ) and include( ) we can use following example.


Create three php files call index.php, header.php, footer.php

index.php

<?
                require ‘header.php’;
                echo ‘<p>’;
                require ‘footer.php’;
?>
#Require mandates file existence

header.php
 <?
                echo ‘I’m Header’;
?>

footer.php      
<?
                echo ‘I’m Footer’;
?>

Loach index.php in browser

You can use include() function in same way. For both functions parenthesis are optional.

Exercise:
Try same program with include.

Without creating the header1.php file change the Index file to include header1.php on behalf of  header.php

require  ‘header1.php’;
Examine the output.
Do the same thing files that use Include() function.
include ‘header1.php’
Examine the output and find the deference

Including Remote Recourses

<? include ‘http://www.google.lk’; ?>

We can include google within our webpage.

Using this way you can include remote sources to you application.

Let’s move to create Simple Website using server site includes

Create a folder in your server root call webapp1
Create three php files call header.php, footer.php and leftnav.php
To include these files create webpage call index.php
Save all these files in webapp1 folder




















You needs to create Webpage like this using includes.
Design the contactus.php file as follows.