CH 2

You might also like

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

Chapter Two

HTML FORMS AND


SERVER SIDE
SCRIPTING

08/31/2023
HTML Form

 An HTML form on a web page usually comprises a


set of input fields for the user to fill in and submit to
the website.
 HTML defines a tag, <form>, which is used to place
a form on a page.
 Within the form, <input>, <select> and other tags
can be placed in order to obtain data from the user.
 There are several types of widgets that can be placed
on a form to obtain user input, including text fields,
radio buttons, check boxes and drop down boxes. 

08/31/2023
HTML Forms

Two steps are involved:


 First you create the HTML form itself, and
 Then you create the corresponding PHP script that will receive and process the
form data.
The form tags look like:
 <form action="script.php“>

 method="post">
 </form>

The most important attribute of your form tag is action, which is


used to specify where the form will post the contents of its fields to. 
 The method attribute of a form dictates how the data is sent to
the handling
page.

08/31/2023
Form using php

<?php
echo"<html>";
echo"<body>";
echo"<form action=‘welldone.php' method='post'>";
echo" First Name: <input type='text' name='name'/>";
echo"<br>";
echo "Last Name: <input type='text' name='lname'/>";
echo"<br>";
echo"Age: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp; <input type='text' name='age' />";
echo"<br>";
echo"Departement:<select name='dropdown'>";
echo"<option value='Info' selected>IT</option>";
echo"<option value='Inf'>IS</option>";
echo"</select>";
echo"<br>";
echo"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value='Rigister Here' />";
echo"</form>";
echo"</body>";
echo"</html>";
?>

08/31/2023
Cont…

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>&nbsp;&nbsp;
<?php echo $_POST["lname"]; ?> !<br/>
You are <?php echo $_POST["age"]; ?>!years old.<br />
And
you are <?php echo $_POST["dropdown"]; ?> student!
</body>
</html>

08/31/2023
GET and POST

There are two ways the browser client can send


information to the web server.
o The GET Method
o The POST Method
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.
Example:http://www.test.com/index.htm?
name1=value1&name2=value2

08/31/2023
The GET Method

The GET method sends the encoded user information appended to the page
request. The page and the encoded information are separated by the ?
character.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information
to be sent to the server.
GET can't be used to send binary data, like images or word documents, to
the server.
The benefit of using the GET method is that the resulting page can be
bookmarked in the user’s Web browser (since it’s a complete URL).
The data sent by GET method can be accessed using QUERY_STRING
environment variable.
GET is used for requesting information, like a particular record
from a database or the results of a search
(searches almost always use GET)
08/31/2023
Cont…

<?php
 if( $_GET["name"] || $_GET["age"] ) {
 echo "Welcome ". $_GET['name']. "<br />";
 echo "You are ". $_GET['age']. " years old.";

 exit();
 }
?>
<html>
 <body>

 <form action = "<?php $_PHP_SELF ?>" method = "GET">
 Name: <input type = "text" name = "name" /><br>
 Age: <input type = "text" name = "age" />
 <input type = "submit" />
 </form>

 </body>
</html>

08/31/2023
Post Method

The POST method transfers information via HTTP headers.


The information is encoded as described in case of GET
method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size
to be sent.
The POST method can be used to send ASCII as well as binary
data.
The data sent by POST method goes through HTTP header so
security depends on HTTP protocol. By using Secure HTTP
you can make sure that your information is secure.
The PHP provides $_POST associative array to access all
sent information using POST method.

08/31/2023
Cont…

<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";

exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>

08/31/2023
The $_REQUEST variable

The PHP $_REQUEST variable contains the


contents of both $_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get
the result from form data sent with both the GET
and POST methods.
The $_REQUEST syntax is ($_REQUEST['name of
the form field goes here']).

08/31/2023
Cont…

<?php
 if( $_REQUEST["name"] || $_REQUEST["age"] ) {
 echo "Welcome ". $_REQUEST['name']. "<br />";
 echo "You are ". $_REQUEST['age']. " years old.";
 exit();
 }
?>
<html>
 <body>

 <form action = "<?php $_PHP_SELF ?>" method = "POST">
 Name: <input type = "text" name = "name" />
 Age: <input type = "text" name = "age" />
 <input type = "submit" />
 </form>

 </body>
</html>

08/31/2023
Conditionals and Operators

PHP’s three primary terms for creating conditionals are if, else,
and elseif (else if).
Every conditional begins with an if clause:
if (condition) {
// Do something!
}
• An if can also have an else clause:

if (condition) {
// Do something!
} else {
// Do something else!
}

08/31/2023
Cont…

An elseif clause allows you to add more conditions:


if (condition1) {
// Do something!
} elseif (condition2) {
// Do something else!
} else {
// Do something different!
}

switch statement − is used if you want to select one of many


blocks of code to be executed, use the Switch statement. The
switch statement is used to avoid long blocks of if..elseif..else
code.

08/31/2023
Cont…

Syntax
switch (expression){
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}

08/31/2023
What is Operator?

Operators are used to perform operations on variables


and values.
Example: 1 + 2 is equal to 3. Here 1 and 2 are called
operands and + is called operator.
PHP language supports following type of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
Conditional (or ternary) Operators

08/31/2023
Arithmetic operator

08/31/2023
Comparison operator

08/31/2023
Logical operators

08/31/2023
Assignment operator

08/31/2023
Validate Form Data

When processing a form, it’s critical to validate user inputs to


ensure that the data is in a valid format.
In terms of both error management and security, you should
absolutely never trust the data being submitted by an HTML form.
There are two types of validations: client-side & server-side:
The client-side validation is performed in the web browsers of
the users
To validate data at the client side, HTML5 validation
or JavaScript can be used.
 The client-side validation aims to assist legitimate users in
entering data in the valid format before submitting it to the server.

08/31/2023
However, client-side validation doesn’t prevent malicious users
from submitting data that can potentially exploit the application.
The server-side validation validates data in the web server using
PHP. 
Validating form data requires the use of conditionals and any
number of functions, operators, and expressions.
One standard function to be used is isset( ), which tests if a variable
has a value (including 0, FALSE, or an empty string, but not NULL).
isset ()— Determine if a variable is declared and is different
than null
One issue with the isset( ) function is that an empty string tests as
true, meaning that isset( ) is not an effective way to validate text
inputs and text boxes from an HTML form.

08/31/2023
…cont

<?php
  
$str = “Example";
  
if(isset($str)) {
    echo "Value of variable is set";
}
else {
    echo "Value of variable is not set";
}
  
$arr = array();
  
if( !isset($arr[0]) ) {
    echo "\nArray is Empty";
}
else {
    echo "\nArray is not empty";
}
?>
08/31/2023
Cont…

To check that a user typed something into textual elements, you can use
the empty( ) function.
It checks if a variable has an empty value: an empty string, 0,
NULL, or FALSE.
What is the difference between isset() and empty()?
 The first aim of form validation is seeing if something was entered or selected in form
elements.
 The second goal is to ensure that submitted data is of the right type (numeric, string, etc.),
of the right format (like an email address), or a specific acceptable value (like $gender being
equal to either M or F ).
 Example:
if (!empty($_REQUEST['name'])) {
$name = $_REQUEST['name'];
} else {
$name = NULL;
echo '<p class="error">You forgot to enter your name!</p>';
}

08/31/2023
Cont…

Example:// email validation


if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
}

08/31/2023
Array

An array is a is a type of data structure that allows us to


store multiple elements of similar data type under a
single variable 
An array is a special variable, which can hold more than
one value at a time.
In PHP, there are three kind of arrays:
 Numeric array - An array with a numeric index where values are
stored linearly.
 Associative array - An array with a string index where instead of
linear storage, each value can be assigned a specific key.
 Multidimensional array - An array containing one or more
arrays

08/31/2023
Numeric Array

These arrays can store numbers, strings and any


object but their index will be represented by
numbers. By default array index starts from zero.
Here we have used array() function to create array.
This function is explained in function reference.
<?php
// Define an indexed array
$colors = array("Red", "Green", "Blue");
?>

08/31/2023
Cont…

The above example is equivalent to the following


example, in which indexes are assigned manually:
<?php
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
?>

08/31/2023
Accessing numeric arrays using loops

$arrLength = count($colors);
for($x = 0; $x < $ arrLength; $x++) {
    echo $colors[$x];
    echo "<br>";
// outputs
Red
Green
Blue
or
for($i=0; $i<3; $i++)
echo $colors[$i]];

08/31/2023
Associative array

each ID key or index is associated with a value


we can use values as keys and assign values to them
Associative arrays are arrays that use named keys
that you assign to them.
<?php
// Define an associative array
$ages = array(“Mulu"=>22, “Ahmed"=>32,
"John"=>28);
?>

08/31/2023
Accessing Associative Arrays

We can loop through the associative array in two ways. First by using for loop
and secondly by using foreach.
Using foreach loop:
foreach ($array as $value) {
// Do something with $value.
}
The foreach loop will iterate through every element in $array, assigning
each element’s value to the $value variable.
To access both the keys and values, use
foreach ($array as $key => $value) {
echo "The value at $key is $value.";
}
You can use any valid variable name in place of $key and $value, like just $k
and $v, if you’d prefer.

08/31/2023
Cont…

Example
<?php
$age = array(“Abebe"=>"35", "Ben"=>"37",
"Joe"=>"43");
echo “abebe is " . $age[‘abebe'] . " years old.";
?>
foreach($age as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";}

08/31/2023
Multidimensional array

Multidimensional array is nothing just its is a


nested of arrays.
each element in the main array can also be an
array

08/31/2023
Accessing Multidimensional array

08/31/2023
Cont…

08/31/2023
Array operators

08/31/2023
Sorting arrays

One of the many advantages arrays have over the other variable
types is the ability to sort them.
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to
the value
ksort() - sort associative arrays in ascending order, according to
the key
arsort() - sort associative arrays in descending order, according
to the value
krsort() - sort associative arrays in descending order, according
to the key

08/31/2023
Sorting Arrays
<?php
$HU = array("CCI","Agri", "FBE", "IOT");
 sort($HU);
$clength = count($HU);
for($x = 0; $x < $clength; $x++) {
 echo $HU[$x];
 echo "<br>";
}
?> //out put agri, cci,fbe,iot
?>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
    echo $numbers[$x];
    echo "<br>";
}
?>
// out puts 2,4,6,11,22

08/31/2023
Php Loops

The while statement will execute a block of code if and as long as a condition is
true.
The while loop looks like this:
while (condition) {
// Do something.
}
The while loop will most frequently be used when retrieving results from a
database.
The for statement is used when you know how many times you want to
execute a statement or a list of statements.
The for loop has a more complicated syntax:
for (initial expression; condition; closing expression) {
// Do something.
}

08/31/2023
Cont…

The functionality of both loops is similar enough that for and


while can often be used interchangeably.
Still, experience will reveal that the for loop is a better choice for
doing something a known number of times.
Whereas while is used when a condition will be true an
unknown number of times.
The do...while statement will execute a block of code at least
once - it then will repeat the loop as long as a condition is true.
do {
//Do something.
}
while (condition);

08/31/2023
Cont…

Example:
// Make the days pull-down menu:
echo '<select name="day">';
for ($day = 1; $day <= 31; $day+ +) {
echo "<option value=\"$day\">$day</option>\n";
}
echo '</select>';
// Make the years pull-down menu:
echo '<select name="year">';
for ($year = 2011; $year <= 2021;$year+ +) {
echo "<option value=\"$year\">$year</option>\n";
}
echo '</select>';

08/31/2023
PHP Regular Expressions

Regular Expressions, commonly known as "regex" or


"RegExp", are a specially formatted text strings used to find
patterns in text. 
They used for effective and efficient text processing and
manipulations.
  For example, it can be used to verify whether the format of
data i.e. name, email, phone number, etc. entered by the user
was correct or not, find or replace matching string within
text content, and so on.
PHP (version 5.3 and above) supports Perl (Practical
Extraction and Report Language) style regular expressions
via its preg_ family of functions. 

08/31/2023
Cont…

overview of the commonly used PHP's built-in


pattern-matching functions 

08/31/2023
Cont…

08/31/2023
Cont…

Example
<?php $pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe."; if(preg_match($pattern,
$text))
{
echo "Match found!";
}
Else
{
echo "Match not found.";
}
?>

08/31/2023
O F T H E
END
A P T E R
CH
08/31/2023

You might also like