Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 50

Chapter 2:

Handling User Input:


Using HTML forms with PHP
The Objective:
Learn how to build forms, and
how to capture the data from
a form with a PHP program.

1
Using HTML form with PHP
– One of the advantages of PHP has always been the ability to easily
manipulate information submitted by the user through an HTML
form.
– Sending data to a script via an HTML form
– The post vs. get methods
– Name value pairs
– Capturing and using data sent via an HTML form.
• What is a HTML FORM?
– A form basically contains boxes and buttons
– Provides two-way communication between web servers
and browsers.
– Demand for most of the emerging applications.
– Providing dynamic contents.
2
FORM Tags and Attributes
• Several tags are used in connection with
forms:
<form> …… </form>
<input>
<textarea> …… </textarea>
<select> …… </select>

3
<FORM> …… </FORM> Tag

• This tag is used to bracket a HTML form. All objects must be


inside of a form tag
– Includes attributes which specify where and how to
deliver filled-up information to the web server.
• All objects inside a form tag have name and value
attributes.
<form action="processForm.php"
name="myForm" method="get"></form>
Attributes
• Action – the URL of the script that the data will be sent to –
this is the page that will display once the submit button is
clicked
• Name – the name of the form
• Method – the way the data is sent to the script.Two main
attributes: get, post

4
METHOD:
◦ Indicates how the information in the form will be
sent to the web server when the form is submitted.
◦ Two possible values:
 POST: causes a form’s contents to be parsed one element
at a time.
 GET: concatenates all field names and values in a single
large string.
◦ POST is the preferred method because of string
size limitations in most systems.

5
• ACTION:
– Specifies the URL of a program on the origin
server that will be receiving the form’s
inputs.
– Traditionally called Common Gateway
Interface (CGI).
– The specified program is executed on the
server, when the form is submitted.
• Output sent back to the browser.

6
<INPUT> Tag
• This tag defines a basic form element.
• Several attributes are possible:
• TYPE
• NAME
• SIZE
• MAXLENGTH
• VALUE
• SRC
• ALIGN

7
TYPE:
◦ Defines the kind of element that is to be
displayed in the form.
 “TEXT” – defines a text box, which provides a
single line area for entering text.
 “RADIO” – radio button, used when a choice
must be made among several alternatives
(clicking on one of the buttons turns off all others
in the same group).
 “CHECKBOX” – similar to the radio buttons, but
each box here can be selected independently of
the others.
8
◦ “PASSWORD” – similar to text box, but characters are
not shown as they are typed.
◦ “HIDDEN” – used for output only; cannot be
modified (mainly used to refer to choices that have
already been made earlier).
◦ “IMAGE” – used for active maps. When the user
clicks on the image, the (x,y) co-ordinates are stored
in variables, and are returned for further processing.
◦ “SUBMIT” – creates a box labeled Submit; if clicked,
the form data are passed on to the designated CGI
script.
◦ “RESET” – creates a box labeled Reset; if clicked,
clears a form’s contents.
9
NAME:
◦ Specifies a name for the input field.
◦ The input-handling program (CGI) in reality
receives a number of (name,value) pairs.
SIZE:
◦ Defines the number of characters that can be
displayed in a TEXT box without scrolling.
MAXLENGTH:
◦ Defines the maximum number of characters a TEXT
box can contain.

10
VALUE:
◦ Used to submit a default value for a TEXT or
HIDDEN field.
◦ Can also be used for specifying the label of a
button (renaming “Submit”, for example).
SRC:
◦ Provides a pointer to an image file.
◦ Used for clickable maps.
ALIGN:
◦ Used for aligning image types.
◦ ALIGN = TOP | MIDDLE | BOTTOM
11
<TEXTAREA> … </TEXTAREA> Tag
• Can be used to accommodate multiple text
lines in a box.
• Attributes are:
– NAME: name of the field.
– ROWS: number of lines of text that can fit into the
box.
– COLS: width of the text area on the screen.

12
<SELECT> …. </SELECT> Tag
Used along with the tag <OPTION>.
Used to define a selectable list of elements.
◦ The list appears as a scrollable menu or a pop-up
menu (depends on browser).
Attributes are:
◦ NAME: name of the field.
◦ SIZE: specifies the number of option elements that
will be displayed at a time on the menu. (If actual
number exceeds SIZE, a scrollbar will appear).

13
MULTIPLE: specifies that multiple
selections from the list can be made.
<FORM ………….>
……..
Languages known:
<SELECT NAME=“lang” SIZE=3 MULTIPLE>
<OPTION> English
<OPTION> Amharic
<OPTION> Afan Oromo
<OPTION> Tigrigna
</SELECT>
</FORM>

14
Example 1

<HTML>
<HEAD>
<TITLE> Using HTML Forms </TITLE>
</HEAD>
<BODY TEXT="#FFFFFF" BGCOLOR="#0000FF“
LINK="#FF9900" VLINK="#FF9900“
ALINK="#FF9900">
<CENTER><H3> Student Registration Form </H3>
</CENTER>
Please fill up the following form about the courses
you will register for this Semester.
15
<FORM METHOD="POST" ACTION="/cgi/feedback">
<P> Name: <INPUT NAME="name" TYPE="TEXT“ SIZE="30"
MAXLENGTH="50">
<P> Roll Number: <INPUT NAME="rollno“ TYPE="TEXT"
SIZE="7">
<P> Course Numbers:
<INPUT NAME="course1" TYPE="TEXT" SIZE="6">
<INPUT NAME="course2" TYPE="TEXT" SIZE="6">
<INPUT NAME="course3" TYPE="TEXT" SIZE="6">
<P> <P> Press SUBMIT when done.
<P> <INPUT TYPE="SUBMIT">
<INPUT TYPE="RESET">
</FORM> </BODY> </HTML>

16
17
The following example uses a simple information form that consists of two
text fields, two checkboxes, and a select box that permits multiple entries:
<html> <head><title>Tour Information</title></head> <body>
<h2>Mission Information</h2>
<form action="formaction.php">
<table width="100%">
<tr><td>Transport Name:</td><td><input type="text"
name="ship" /></td></tr>
<tr><td>Trip Date:</td><td><input type="text" name="tripdate"
/></td></tr>
<tr><td colspan="2">Mission Goals:</td></tr>
<tr>
<td><input type="checkbox" name="exploration" value="yes" />
Exploration</td>
<td><input type="checkbox" name="contact" value="yes" />
Contact</td>

18
</tr> <tr>
<td valign="top">Language Choice </td>
<td>
<select name=“language" multiple="multiple">
<option value=“amharic">Amharic</option>
<option value=“english">English</option>
<option value=“spanish">Spanish</option>
</select>
</td>
</tr>
<tr><td colspan="2" align="center"><input type="submit"
/></td></tr>
</table>
</form> </body> </html>

19
20
Two-tier Software Architecture

2. Server retrieves PHP page


1. Browser sends from storage
URL to request
PHP page
Web - compiles PHP code
client server
- starts program
3. Sends results
to client -replaces code with
code outputs

4. Browser
displays page

21
Example– simple calculation (arithmetic, for-loop)
makes HTML wrapper

1. Make HTML Form


that sends name and integers M and N
to PHP script.
2. PHP Script:
Gets Form data.
Sends multiples up to M * N, to browser
on successive lines.

22
HTML Form requests simple calculation

m1.html HTML Form Sends data


Requests PHP execution

m1.php PHP program Gets data from Server

Calculation

HTML wrapper

23
Architecture Overview for Example

data for
program program
submits requested query-string
Form
m1.php ?NAME=abebe &M=2&N=2
retrieves m1.php

compiles m1.php
m1.html starts program

results to client data Gets Name, M, N values

Calculates based on input


and sends results to browser

Browser show_source (“m1.php”)


renders page

24
HTML FORM Example Code Overview
LAYOUT
PHP program requested
Form data/variables

<form action="m1.php" method=:”get” >

<input type="text" name="NAME" /> NAME <br>

<input type="text" name="M" /> M <br>

<input type="text" name="N" /> N <br>

<input type="submit" value ="Press" />

</form >
activates Form: sends data to server

asks server to execute m1.php 25


PHP File
Layout fileName.php

Initial HTML

<?php

PHP statements here ;

?>

More HTML

<?php

PHP statements here ;

?>

More HTML
26
<html><head>
<style type="text/css">
body { background-color: cyan ; font-size:18pt ; }
</style>
</head><body>
PHP code for calculations
HTML Code sends products
<?php
Form variable 1*1
Gets..data
M *MN & N from server
$M = $_GET[ "M" ]; names to browser
$N = $_GET[ "N" ]; PHP variables begin with $
print "Here come the multiples!<br><br>" ; Sends output stream
to browser
PHP for ( $i=1 ; $i <= $M; $i++ )
{ names
variable print "<br>" ; Typical for-loop
for ( $k=1 ; $k <= $N; $k++ )
{ $x = $i * $k ; Nested for-loop
print "$i * $k = $x" ; See with: dynamic HTML
Generates
print "<br>" ; View > Page Source
} Intermingled
}; HTML and text.
print "That's all folks<br><br>" ;
show_source("m1.php"); Displays PHP code.
?>
27
</body></html>
Calculator.html
<html>
<h1><center>Calculator</center></h1>
<form action="calculator.php" method="post">
<table align="center">
<th> Choose arithmetic operator<th>Enter the values </th>
<tr><td>+<input type="radio" name="arithmetic" value="add"
checked><td><input type="text" name="v1">
<tr><td>- <input type="radio" name="arithmetic"
value="minus"><td><input type="text" name="v2">
<tr><td>/ <input type="radio" name="arithmetic" value="divide">
<tr><td>*<input type="radio" name="arithmetic" value="multiply">
<tr><td><input type="submit" value="Execute" >
</table>
<h3> the Result</h3>
</form>
</html>
28
Calculator.php
<?php
$v1=$_POST['v1'];
$v2=$_POST['v2'];
$a=$_POST['arithmetic'];
require('calculator.html');
switch($a){
case 'add':
echo $v1+$v2;
break;
case 'minus':
echo $v1-$v2;
break;
case 'divide':
{if ($v2==0)echo"Cannot divide by zero";
else echo $v1/$v2;
break;}
case 'multiply':
echo $v1*$v2;
break;
}
?> 29
30
PHP GET and POST Methods

• The PHP $_GET and $_POST variables are used


to retrieve information from forms, like user
input
• Form elements in an HTML/PHP page will
automatically be available to your PHP scripts.

31
PHP GET and POST Methods….
• Before the browser sends the information, it
encodes it using a scheme called URL encoding. In
this scheme, name/value pairs are joined with
equal signs and different pairs are separated by
the ampersand.
name1=value1&name2=value2&name3=value3
• Spaces are removed and replaced with the +
character and any other non-alphanumeric
characters are replaced with a hexadecimal values.
• After the information is encoded it is sent to the
server.

32
What are the differences between GET and POST methods in form
submitting, give the case where we can use GET and we can use
POST?
– When you want to send short or small data, not
containing ASCII characters, then you can use GET”
Method.
– But for long data sending, say more then 100
character you can use POST method.
– Once most important difference is when you are
sending the form with GET method.
– You can see the output which you are sending in the
address bar.
– Whereas if you send the form with POST” method
then user can not see that information.
33
$_POST
• The $_POST variable is an array of variable
names and values sent by the HTTP POST
method
• The $_POST variable is used to collect values
from a form with method="post“
• Information sent from a form with the POST
method is invisible to others and has no limits
on the amount of information to send

34
Example - $_POST

<!--“welcome.html” file --> <!--“welcome.php” file -->

<html> <body> <html> <head>


<form action=“welcome.php" <title>Grab form values</title>
method="post"> </head> <body>
Name: <input type="text" Welcome <?php echo
name="name"> $_POST["name"];?>.<br/>
Age: <input type="text"
name="age"> You are <?php echo
<input type="submit"> $_POST["age"];?> years old
</form>
</body></html> </body> </html>

35
$_GET
• The $_GET variable is an array of variable
names and values sent by the HTTP GET
method
• The $_GET variable is used to collect values
from a form with method="get“
• Information sent from a form with the GET
method is visible to everyone (it will be
displayed in the browser's address bar) and
it has limits on the amount of information
to send (max. 100 characters)
36
Example - $_GET

<!--“welcome.html” file --> <!--“welcome.php” file -->

<html> <html>
<body> <head>
<title>Grab form values</title>
<form action=“welcome.php" </head>
method="get">
Name: <input type="text" <body>
name="name"> Welcome <?php echo
$_GET["name"];?>.<br/>
Age: <input type="text"
name="age"> You are <?php echo $_GET["age"];?>
<input type="submit"> years old
</form> </body>
</body>
</html> </html>
37
The $_REQUEST Variable
• The PHP $_REQUEST variable can be used
to get the result from form data sent with
both the GET and POST methods as well as
$_COOKIE.
Example
Welcome <?php echo $_REQUEST["name"]; ?
>.<br />
You are <?php echo $_REQUEST["age"]; ?> years
old!

38
Why use $_POST?
– Variables sent with HTTP POST are not
shown in the URL.
– The POST requests are not idempotent. This
means that they cannot be cached, and the
server is recontacted every time the page is
displayed. Because of this, it is not possible
to bookmark the page.
– Variables have no length limit

39
Form Validation
• User input should be validated whenever possible.
• You can validate the form input on two places,
 client side (done with javascript)
 server side (done with PHP)

• Client side validation is faster, and will reduce


server load.
• For security reason, use server side validation if
the form accesses a database.
• Server side form validation with PHP can act as a
backup just in case the user switch off javascript
support on the browser.
40
Form Validation….
• Form validation must be carried out on every
form element to guarantee that the input is
correct and processing incorrect input values
can make your application give unpredictable
result.
• A good way to validate a form on the server is
to post the form to itself, instead of jumping
to a different page. The user will then get the
error messages on the same page as the form.
This makes it easier to discover the error.
41
Form Validation…..
Make sure the data
 Is in the correct format
▪ A number is an integer
▪ A name is in the form of a string
▪ An email is in the format of an email
 Is not empty
 Does not have any code you don’t want it to have
 Length

42
Main PHP Validation Functions: I
 The first step in validation is making sure
variables aren’t empty
 Unfortunately, a field filled with spaces is not
technically empty
 That’s why you need the trim() function
 How it works:
 Pass it a variable and
 It removes white spaces before or after a field entry
(in the variable)
 Do it like so…
$name = trim($name);
Main PHP Validation Functions: II
 empty() – checks to see if a variable is empty or not
 Pass it a variable
 If the variable has no value (it’s empty), it returns True
▪ “Yes, it is empty”
 If the variable does have a value (not empty), it returns False
▪ “No, it’s not empty”
 The empty() function in its natural habitat
 Typically, you use the empty() function to check to see if it is not empty
▪ For this, you use the special NOT code, “!”
▪ Place the exclamation mark (NOT) in front of the function
 Example:
▪ if (!empty($variable)) {
echo ‘<p>It’s not empty</p>
}
else {
echo ‘<p>It is empty</p>
}
▪ In plain English, if(!empty($variable)) means “If variable is NOT empty,…”
▪ The keyword, “else” is like saying, “otherwise…”
e.g.
• The easiest way to check to see if a user has typed in a value in
the text boxes is to use the empty() function.
Example:
if (!empty($_POST['fname'])){
$msg = "fname;
$_POST[fname] ";
}
else
{
$fname = NULL;
echo "Please fill out your first name.
";
}

45
e.g.

 Use the preg_match() function


 No, it is not a paternity test
 It stands for perform a regular expressions match
<?php
$age=$_POST["age"];

if(!preg_match("/^[0-9]$/",$age))

echo "You enterd invaid input, please try again";


else
echo "Your age is ". $age;

?>
46
e.g.
<?php
$age=$_POST["age"];

if(!preg_match("/^[0-9]{1,3}$/",$age))

echo "You enterd invaid input, please try again";


else
echo "Your age is ". $age;

?>
47
Form Validation with PHP
• Using the preg_match function()
• preg_match() is a case sensitiv function, which
means it treats “a” and “A” differently.
• Example
function check_field1($field_name_1)
{
if(!preg_match("/[^a-zA-Z0-9]+$/”,
$field_name_1)) The slashes “/” and “/” are delimiters, “^”
return TRUE; marks the start of string or line and the Dollar
sign “$” the end of the string, or line. The plus-
else symbol “+” means required.
return FALSE;
}
48
/^[a-zA-Z0-9 _-.,:"']+$/
• We translate this regexp as:
• From the beginning to the end of the address
string check if our character is one of the
following a-z, A-Z, 0-9, space, underscore,
dash, dot, comma, semicolons, double and
sigle quotes. You can add any character that
you think may be part of an address.

49
Refer the following PHP Built-in Functions

• Trim()
• Empty()
• Preg_match()
• Preg_replace()
• html_entities()
• Htmlspecialcharacters()
• Add_slashes()
• Strip_slashes()
• Mail()

You might also like