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

Chapter 3 Web Form Slide 1

CHAPTER 3:
Web Form
Topics covered:-
• Server-Side/Client-Side Web Scripting
• Superglobals Variables
• Web Form
• Validation
• Including Multiple Files
• Sticky Forms

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 2

Learning Outcomes
At the end of this chapter, you should be able to
• Explain what server-side scripting is.
• Write scripts accessing to superglobal variables
• Create and process Web forms
• Build forms with multiple included files
• Create sticky forms

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 3

Server-Side Web Scripting (1)


• Server-side web scripting is a web server technology in which a
user's request is fulfilled by running a script directly on the
web server to generate dynamic web pages.
• In client-side web scripting, scripts are run by the viewing web
browser, usually in JavaScript.
• Advantage to server-side web scripting
• ability to highly customize the response based on the user's
requirements and access rights
• allows queries into data stores.

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 4

Server-Side Web Scripting (2)


• Examples of server-side scripting languages:-
• PHP
• ASP/ASP.NET
• Perl
• Python
• Ruby
• ColdFusion

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 5

PHP (1)
• PHP is used generally for form handling, file processing,
and database access.
• PHP code is placed in the body of an HTML document.
<!- - example.php
<html>
<head><title> Trivial php example </title>
</head>
<body>
<?php
echo "The current time is ".date('F j, Y');
?>
</body>
</html>
AMIT 2043 Web Systems and Technologies
Chapter 3 Web Form Slide 6

PHP (2)
● A web browser requests a document (indicated by a file
ending .php) from the web server.
● The web server will locate the file on its hard-drive, interpret
(using the PHP interpreter) and execute its contents.
● The result is a dynamically assembled HTML code that is then
sent back to the browser which renders the HTML code into a
web page.

Request
index.php

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 7

Superglobals Variables (1)


• Superglobals are predefined global arrays that provide
information about server, environment, and user input
$GLOBALS Contains a reference to every variable which is currently
available within the global scope of the script.
$_SERVER Variables set by the web server or otherwise directly related to the
execution environment of the current script.
$_GET Variables provided to the script via URL query string.
$_POST Variables provided to the script via HTTP POST
$_COOKIE Variables provided to the script via HTTP cookies.
$_FILES Variables provided to the script via HTTP post file uploads.
$_ENV Variables provided to the script via the environment.
$_REQUEST Variables provided to the script via the GET, POST, and
COOKIE input mechanisms

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 8

Superglobals Variables (2)


<?php # predefined.php

// Create a shorthand version of the variable names:


$file = $_SERVER['SCRIPT_FILENAME'];
$user = $_SERVER['HTTP_USER_AGENT'];
$server = $_SERVER['SERVER_SOFTWARE'];

// Print the name of this script:


echo "<p>You are running the file:<br /><b>$file</b>.</p>\n";

// Print the user's information:


echo "<p>You are viewing this page using:<br /><b>$user</b></p>\n";

// Print the server's information:


echo "<p>This server is running:<br /><b>$server</b>.</p>\n";
?>
AMIT 2043 Web Systems and Technologies
Chapter 3 Web Form Slide 9

Creating & Processing Web Form


• An HTML form is created using the form tags and various
elements for taking input.
Syntax of the form tag

<form action=”script.php” method=”post”>



</form>

• Action attribute: Identifies the program on the Web server


that will process the form data when it is submitted
• Method attribute: Specifies how the form data will be sent
to the processing script

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 10

Method Attribute (1)


• The value of the method attribute must be either “post” or “get”
• The “post” method embeds the form data in the request
message
• The “get” method appends the form data to the URL specified
in the form’s action attribute
• When a Web form is submitted using the “post” (or “get”)
method, PHP automatically creates and populates a $_POST array
(or $_GET) array

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 11

Handling Web Forms (1)


• Form fields are sent to the Web server as a name/value
pair via the $_POST or $_GET array
• The name portion of the name/value pair becomes
the key of an element in the $_POST or $_GET
array, depending on which method was used to
submit the data
• The value portion of the name/value pair is
populated by the data that the user enters in the
input control on the Web form

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 12
<form action="handle_form.php" method="post"> <body>
<fieldset><legend>Enter your information in the form below:</legend> <?php // handle_form.php

<p><b>Name:</b> <input type="text" // Create a shorthand for the form data:


name="name" size="20" maxlength="40" /></p> $name = $_POST['name'];
$email = $_POST['email'];
<p><b>Email Address:</b> <input type="text" name="email" size="40"
maxlength="60" /></p> $comments = $_POST['comments'];

<p><b>Gender:</b> <input type="radio" name="gender" value="M" /> Male


<input type="radio" name="gender" value="F" /> Female</p> // Print the submitted information:
echo "<p>Thank you, <b>$name</b>, for the
<p><b>Age:</b><select name="age"> following comments:<br />
<option value="0-29">Under 30</option> <tt>$comments</tt></p> ";
echo "We note that you know the following
<option value="30-60">30 - 60</option> languages: ";
$languages = $_POST['languages'];
<option value="60+">Over 60</option></select></p>
foreach ($languages as $language) {
<p><b>Seect the languages you know</b></p> print "<li>$language</li>";
}
<p><input type="checkbox" name="languages[]" id="Perl" value="Perl" />
print '</ul>';
<label for="Perl">Perl</label></p>
< p><input type="checkbox" name="languages[]" echo "<p>We will reply to you at
<i>$email</i>.</p>\n";
id="JavaScript" value="JavaScript" />
<label for="JavaScript">JavaScript</label></p> ?>
<p><b>Comments:</b> <textarea name="comments" rows="3" </body>
cols="40"></textarea></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit My
Information" /></div></form>

AMIT 2043 Web Systems and Technologies example 2\form.html


Chapter 3 Web Form Slide 13

Handling Web Forms (2)


• Data entered by user into an element can also be accessible
via $_REQUEST[‘element’].
• $_POST and $_GET and $_COOKIE are subsets of
$_REQUEST
• One aspect of good security and programming is to be
precise when referring to a variable. Thus, try not to use
$_REQUEST.
• PHP is case-sensitive when it comes to variable names.
<input type="text" name="name" >
Eg
$_ POST [‘name’] is valid

$_ Post [‘name’] or $_ POST [‘Name’] will have no value.

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 14

Validating a Web Form (1)


• Validating form data includes
• Verifying that a value has been entered or an item selected
• Verifying that submitted value is of the
⮚ Right data type
⮚ Right format
⮚ Acceptable value
• The best way to ensure valid form data is to build the Web
form with controls (such as check boxes, radio buttons, and
selection lists) that only allow the user to select valid
responses
• Unique information, such as user name, password, or e-mail
must be validated
AMIT 2043 Web Systems and Technologies
Chapter 3 Web Form Slide 15

Validating a Web Form (2)


• When form data is sent using the “post” or “get” method, all
controls get sent to the server even if they do not contain data
(except unchecked radio buttons and checkboxes)
• Functions for determining if form variables contain values
✔isset(): which tests if a variable has a value (including 0, FALSE,
or an empty string, but not NULL).
✔empty(): is used to determine if a variable contains a value
• The empty() function returns FALSE if the variable being checked
has a nonempty and nonzero value, and a value of TRUE if the
variable has an empty or zero value

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 16
<? php //validate_form1.php
if (!empty($_POST['name'])) {
$name = $_ POST['name'];
} else {
$name = NULL;
echo '<p class="error">You forgot to enter your name!</p>';
} ………
if (isset($_ POST['gender'])) {
$gender = $_ POST['gender'];
if ($gender == 'M') {
echo '<p><b>Good day, Sir!</b></p>';
} elseif ($gender == 'F') {
echo '<p><b>Good day, Madam!</b></p>';
} else { // Unacceptable value.
$gender = NULL;
echo '<p class="error">Gender should be either "M" or "F"!</p>';
}
} else { // $_ POST['gender'] is not set.
$gender = NULL;
echo '<p class="error">You forgot to select your gender!</p>';
}
if ($name && $email && $gender && $comments) {
echo "<p>Thank you, <b>$name</b>, for the following comments:<br />
<tt>$comments</tt></p>
<p>We will reply to you at <i>$email</i>.</p>\n";
} else { // Missing form value.
echo '<p class="error">Please go back and fill out the form again.</p>';
} ?>

AMIT 2043 Web Systems and Technologies example 3\validate_form1.php


Chapter 3 Web Form Slide 17

Validating a Web Form (3)


• Validating Data by Type
• is_array(), is_bool(), is_float(),
is_int(), is_null(), is_string(),
is_scalar()
• is_numeric() – also can be used to check whether a
string contains numeric data (e.g., '20')
• is_resource() for checking whether submitted data is
a resource, like a database connection

• Typecasting - forcibly casting a variable’s type can be a


good security measure
$var = 20.2;
echo (int) $var; // 20
$var = 20;
echo (float) $var; // 20.0

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 18
<?php //calculator.php
// Cast all the variables to a specific type:
$quantity = (int) $_POST['quantity'];
$price = (float) $_POST['price'];
$tax = (float) $_POST['tax'];
// All variables should be positive!
if ( ($quantity > 0) && ($price > 0) && ($tax > 0) ) {
// Calculate the total:
$total = ($quantity * $price) * (($tax/100) + 1);
// Print the result:
echo '<p>The total cost of purchasing ' . $quantity . ' widget(s) at RM' .
number_format ($price, 2) . ' each, plus tax, is RM' .
number_format ($total, 2) . '.</p>';
} else { // Invalid submitted values.
echo '<p style="font-weight: bold; color: #C00">Please enter a valid quantity,
price, and tax rate.</p>';
} ?>
AMIT 2043 Web Systems and Technologies example 4\calculator.php
Chapter 3 Web Form Slide 19

Validating a Web Form (4)


• Regular expression functions are some of the
best tools for verifying that string data meets the
strict formatting required for e-mail addresses,
Web page URLs, or date values.

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 20
<?php # validate_form2.php
// Validate the name:
if (preg_match("/[a-zA-Z ]+$/", $_POST['name'])) {
$name = trim($_POST['name']);
} else {
echo '<p class="error">The name is empty or has illegal characters!</p>';
$error = true;
}
// Validate the email:
if (preg_match("/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/", $_POST['email'] )){
$email = trim($_POST['email']);
}else {
echo '<p class="error">The email is empty or has illegal characters!</p>';
$error = true;
} example 5\validate_form2.php
if (!$error) {
echo "<p>Thank you, <b>$name</b>, for the feedback:<br />
<p>We will reply to you at <i>$email</i>.</p>\n";
} else {
echo '<p class="error"> Please go back and fill out the form again.</p>';
} ?>

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 21

Redisplaying the Web Form (1)


• When processing a Web form, it is best to track any errors on
the form during processing and then redisplay the form for the
user to correct all the errors at one time
• To achieve this, a conditional must check which action (display
or handle) should be taken:

if (/* form has been submitted */) {


// Validate and Handle it.
} else {
// Display it.
}

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 22

Redisplaying the Web Form (2)


• Use a flag variable whose existence will be checked to
determine whether or not to handle the form
<input type=”hidden” name=”submitted” value=”1” />

if (isset($_POST[‘submitted’])) {
// Validate and Handle it.
} else {
// Display it.
}
Or
if (isset($_POST[‘submitted’])) {
// Validate and Handle it.
}
// Display form
calculator.php
AMIT 2043 Web Systems and Technologies
Chapter 3 Web Form Slide 23

Including Multiple Files (1)


● PHP allows one to divide scripts and Web sites into distinct parts,
by using external files to separate out commonly used processes.
● PHP has four functions for using external files:
● include()
● include_once()
● require()
● require_once()
● To use them, the PHP script would have a line like
include_once(‘C:/php/includes/filename.php’);
require(‘/path/to/filename.html’);
● The function will take all the content of the included file and drop
it in the parent script (the one calling the function) at that juncture.
● Either absolute or relative pathname can be used.

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 24
homePage.php

multiple-files\homePage.php

eader.html

Calculator.php

footer.html

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form <body> Slide 25
<!-- header.html -->
<?php # homePage.php <div id="header">
$page_title = 'Welcome to this <h1>Your Website</h1>
Site!'; <h2>catchy slogan...</h2>
include ('includes/header.html'); </div>
?> <div id="navigation">
<ul>
<li><a href=“homePage.php">Home Page</a></li>
<h1>Welcome to the Home Page</h1> <li><a href="calculator.php">Calculator</a></li>
<li><a href="dateform.php">Date Form</a></li>
<li><a href="#">link four</a></li>
<p>This is where the page-specific <li><a href="#">link five</a></li>
content goes. This section, and the </ul>
corresponding header, will change from
one page to the next.</p> </div>
<div id="content"><!-- Start of the page-specific content. -->
<!-- footer.html -->
……..
<!-- End of the page-specific content. --></div>
<?php <div id="footer">
include ('includes/footer.html'); <p>Copyright &copy; <a href="#">Plain and
……
?> </p>
</div>
</body>
</html>
AMIT 2043 Web Systems and Technologies
Chapter 3 Web Form Slide 26

Including Multiple Files (2)


• Difference between include() and require() functions
• A warning will be printed to the Web browser if an
include() function doesn’t work (it cannot include the
file for some reason), but the script will continue to
run.
• The PHP script will be halted if require() fails.
• include_once() and require_once() guarantee that the
external file is included only once disregard the no. of
times a script may attempt to include it.

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 27

Including Multiple Files (3)


• Advantages of using external files for holding standard
procedures (i.e., PHP code), CSS, JavaScript, and the HTML
• Ease of maintaining the web site because commonly edited
code is placed in one central location.
• Improved consistency in applications and design of web
pages
• Security by separating more sensitive data (such as
database access information) from other data.

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 28

Sticky Forms (1)


• A sticky form is used to redisplay the form with the values
the user entered the last time the form was submitted
• Useful when user is required to resubmit a form after filling
it incorrectly.
Eg:
<p>First Name:
<input type="text" name="fName"
value="<?php echo $firstName; ?>“
/>
</p>

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 29

Sticky Forms (2)


Preset a <input type=”radio” name=”gender” value= ”F”
radio <?php if ($gender == ‘F’)) { echo ‘checked=”checked”’; } ?> />
button
Preset a <textarea name=”comments” rows=”10” cols=”50”>
textarea <?php echo $comments; ?>
</textarea>
Preset a echo ‘<select name=”year”>’;
pull-down for ($y = 2011; $y <= 2021; $y++) {
menu echo “<option value=\”$y\”;
if ($year == $y) {
echo ‘ selected=”selected” ’;
}
echo “>$y</option>\n”;
}
echo ‘</select>’;

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 30
<? php
if (isset($_POST['submitted'])) {
if ( is_numeric($_POST['quantity']) && is_numeric($_POST['price']) && is_numeric($_POST['tax']) ) {
$total = ($_POST['quantity'] * $_POST['price']);
$taxrate = ($_POST['tax'] / 100); // Turn 5% into .05.
$total += ($total * $taxrate); // Add the tax.
echo '<h1>Total Cost</h1> <p>The total cost of purchasing ' . $_POST['quantity']
. ' widget(s) at RM' . number_format ($_POST['price'], 2) . ' each, including a tax rate of ‘
. $_POST['tax'] . '%, is RM‘ . number_format ($total, 2) . '.</p>';
} else { // Invalid submitted values.
echo '<h1>Error!</h1>
<p class="error">Please enter a valid quantity, price, and tax.';
}
} // End of main isset() IF.
?>
<h1>Widget Cost Calculator</h1>
<form action="calculator.php" method="post">
<p>Quantity: <input type="text" name="quantity" size="5" maxlength="5"
value="<?php if (isset($_POST['quantity'])) echo $_POST['quantity']; ?>" /></p>
<p>Price: <input type="text" name="price" size="5" maxlength="10"
value="<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /></p>
<p>Tax (%): <input type="text" name="tax" size="5" maxlength="5"
value="<?php if (isset($_POST['tax'])) echo $_POST['tax']; ?>" /></p>
<p><input type="submit" name="submit" value="Calculate!" /></p>
<input type="hidden" name="submitted" value="TRUE" /> calculator2.php
</form>

AMIT 2043 Web Systems and Technologies


Chapter 3 Web Form Slide 31

References
• PHP 6 and MySQL 5 by Ullman, L. Peachpit Press
• PHP Programming with MySQL Second Edition by
Gosselin, D., Kokoska, D. & Easterbrooks, R. Course
Technology

AMIT 2043 Web Systems and Technologies

You might also like