web development (php/mysql)
TRANSCRIPT
Web Development (PHP/MySQL)
Bea May M. Belarmino
1
Table of Contents
Module 5: PHP Operator, Control Structure, Loops 80
Introduction 80
Learning Outcomes 80
Lesson 1: Operator 81
Lesson 2: IF statement 85
Lesson 3: IF ELSE Statement 86
Lesson 4: ELSE IF Statement 87
Lesson 5: SWITCH Statement 87
Lesson 6: WHILE LOOP Statement 89
Lesson 7: DO...WHILE LOOP statement 89
Lesson 8: FOR LOOP Statement 90
Lesson 9: FOREACH LOOP 91
Lesson 10: BREAK/CONTINUE 92
Assessment Task 95
Summary 98
Module 6: PHP Function, Arrays 99
Introduction 99
Learning Outcomes 99
Lesson 1: Function 100
Lesson 2: Function Arguments 101
Lesson 3: Function Returns a Value 101
Lesson 4: Arrays Types of PHP Arrays 102
Assessment Task 110
Summary 112
2
Module 7: PHP Forms 113
Introduction 113
Learning Outcomes 113
Lesson 1: Get And Post Method 114
Lesson 2: Get Method 115
Lesson 3: Post Method 115
Lesson 4: Form Validation 116
Lesson 5: Form Required Fields 120
Lesson 6: Form URL/E-mail 121
Lesson 7: Form Complete 126
Assessment Task 127
Summary 136
Module 8: PHP Cookies And Session 137
Introduction 137
Learning Outcomes 137
Lesson 1: Cookie 138
Lesson 2: Accessing Cookie Value 139
Lesson 3: Deleting A Cookie 139
Lesson 4: Sessions 139
Lesson 5: Starting A PHP Session 140
Lesson 6: Accessing Session Data 140
Lesson 7: Destroying A Session 141
Assessment Task 142
Summary 146
80
MODULE 5
PHP OPERATOR, CONTROL STRUCTURE,
LOOPS
Introduction
Based on the w3schools.com website (2003), Operators are used to perform
operations on variables and values. Very often when you write code, you want to perform
different actions for different conditions. You can use conditional statements in your code to
do this. You will also learn how to repeat code by using loops in PHP on this module.
Learning Outcomes
At the end of this lesson, the student should be able to:
1. Appreciate the importance of using arithmetic operation & control structure in
program.
2. Create simple program using arithmetic operations and execute it in a PHP
program.
3. Create simple program the if/else, if/else/if/else and switch statements and
execute it in a PHP program.
81
Lesson 1: Operator
Based on the w3schools.com website (2003), is something that you feed with one
or more values
characters or set of characters that perform a special operation within the
PHP code (w3schools.com, 2003)
A. Arithmetic Operators
Based on the w3schools.com website (2003), used to perform simple
mathematical operations such as addition, subtraction, multiplication, division,
etc.
Table 5.1 Arithmetic Sample Results (w3schools.com, 2003)
Example Name Result
$a+$b Addition (+) Sum of $a and $b
$a-$b Subtraction (-) Difference of $a and $b
$a*$b Multiplication (*) Product of $a and $b
$a/$b Division (/) Quotient of $a and $b
$a%$b Modulus (%) Remainder of $a divided by $b
$a**$b Exponentiation (**) Result of raising $a to the $b’th power
(PHP5)
B. Assignment Operators
Based on the w3schools.com website (2003), the PHP assignment operators
are used with numeric values to write a value to a variable.
Based on the w3schools.com website (2003), the basic assignment operator
in PHP is “=“. It means that the left operand gets set to the value of the
assignment expression on the right.
82
Table 5.2 Assignment Sample Results (w3schools.com, 2003)
Operator Assignment Same as Description
= a=b a = b The left operand gets the value
of the expression on the right
+= a+=b a = a + b Addition
-= a-=b a = a –b Subtraction
*= a*=b a = a * b Multiplication
/= a/=b a = a / b Division
%= a%=b a = a % b Modulus
C. Comparison Operators
Based on the w3schools.com website (2003), it allows you to compare two
values.
Table 5.3 Comparison Operators Sample Results (w3schools.com, 2003)
Example Name Result
$a = = $b Equal TRUE if $a is equal to $b
$a = = = $b Identical TRUE if $a is equal to $b, and they are of the
same type. (PHP4only)
$a != $b Not equal TRUE if $a is not equal to $b
$a <> $b Not equal TRUE if $a is not equal to $b
$a != = $b Not identical TRUE if $a is not equal to $b, or they are not
of the same type. (PHP 4 only)
$a < $b Less than TRUE if $a is strictly less than $b
$a > $b Greater than TRUE if $a is strictly greater than $b
$a <= $b Greater than TRUE if $a is less than or equal to $b
$a >= $b Greater than
or equal
TRUE if $a is greater than or equal to $b
83
D. Increment/Decrement Operators
Based on the w3schools.com website (2003), increment operators are used
to increase the value of a variable by 1.
Based on the w3schools.com website (2003), decrement operators are used
to decrease the value of a variable by 1.
Table 5.4 Increment/Decrement Operators Sample
Results (w3schools.com, 2003)
Example Name Effect
++$a Pre-increment Increment $a by one. Then returns $a.
$a++ Post-increment Returns $a, then increments $a by one
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
Sample script (w3schools.com, 2003):
<?php
echo “<h3>Postincrement</h3>“;
$a = 5;
echo “Should be 5: “ . $a++ . “<br/> \n”;
echo “Should be 6: “ . $a . “<br/> \n”;
echo “<h3>Preincrement</h3>“;
$a = 5;
echo “Should be 6: “ . ++$a . “<br/>\n”;
echo “Should be 6: “ . $a . “<br/>\n”;
?>
84
E. Logical Operators
Based on the w3schools.com website (2003), used to combine conditional
statements
Table 5.5 Logical Operators Sample Results (w3schools.com, 2003)
Example Name Result
$a and $b AND T RUE if both $a and $b are TRUE.
$a or $b OR TRUE if either $a or $b is TRUE.
$a xor $b XOR TRUE if either $a or $b is TRUE,
but not both.
! $a NOT TRUE if $a is not TRUE.
$a && $b AND TRUE if both $a and $b are TRUE.
$a | | $b OR TRUE if either $a or $b is TRUE.
F. String Operators
two string operators
i. concatenation operator(.) -returns the concatenation of its right and
left arguments (w3schools.com, 2003).
ii. concatenation assignment operator(.=) -appends the argument on the
right side to the argument on the left side (w3schools.com, 2003).
Sample script (w3schools.com, 2003):
<?php$a = “Hello “;
$b = $a . “World!”; // now $b contains “Hello World!”
$a = “Hello “;$a .= “World!”; // now $a contains “Hello World!”
?>
85
G. PHP Array Operators
Based on the w3schools.com website (2003), PHP array operators are used
to compare arrays.
Table 5.6 Logical Operators Sample Results (w3schools.com, 2003)
Example Name Result
$a + $b Union (+) Union of $a and $b
$a = = $b Equality (==) Returns true of $a and $b have
the same value
$a === $b Identity (=== Returns true if $a and $b have
the same value, same order, and
of the same type
$a != $b Inequality (!=) Returns true if $a is not equal to
$b
$a <> $b Inequality (<>) Returns true if $a is not equal to
$b
$a !== $b Not-Identity (!==) Returns true if $a is not identical
to $b
Lesson 2: IF statement
Based on the w3schools.com website (2006), if statement is one of the most
important features of many languages.
It allows conditional execution of code fragments (w3schools.com, 2006).
Use PHP if statement when you want your program to execute a block of code only if
a specified condition is true (w3schools.com, 2006).
Syntax (w3schools.com, 2006) :
If (condition) {
//statement to be executed if condition is true;
}
86
Example (w3schools.com, 2006) :
<?php
$t = date(“H”);
if ($t < “12”) {
echo “Good morning!”;}
?>
Lesson 3: IF ELSE Statement
Based on the w3schools.com website (2006), this control structure executes some
code if conditions is met and do something else if the condition is not met.
Else, extends an if statement to execute a statement in case the condition in the if
statement evaluates to false (w3schools.com, 2006).
Syntax (w3schools.com, 2006):
If (condition) {
//statement to be executed if condition is true;
} else {
//statement to be executed if condition is false;
}
Example (w3schools.com, 2006):
<?php
$t = date(“H”);
if ($t < “12”) {
echo “Good morning!”;
} else {
echo “Good afternoon!”;}
?>
The else statement is only executed if the condition in the if statement is evaluated to
false, and if there were any else if expressions –only if they evaluated to false as well
(w3schools.com, 2006).
87
Lesson 4: ELSE IF Statement
Based on the w3schools.com website (2006), a combination of IF and ELSE
It extends an IF statement to execute a different statement in case the original if
expression evaluates to FALSE (w3schools.com, 2006).
Syntax (w3schools.com, 2006):
If (condition) {
//statement to be executed if condition is true;
} else if(condition) {
//statement to be executed if condition is true;
} else {
//statement to be executed if condition is false;
}
Example (w3schools.com, 2006):
<?php
$t = date(“H”);
if ($t < “12”) {
echo “Good morning!”;}
else if($t < “18”) {
echo “Good afternoon!”;
} else {
echo “Have a good evening!”;
}
?>
Lesson 5: SWITCH Statement
Based on the w3schools.com website (2006), similar to a series of if statements on
the same expression.
88
Syntax (w3schools.com, 2006):
switch (n) {
case 1:
//Statement to be executed if n=case 1;
break;
case 2:
//Statement to be executed if n=case 2;
break;
case 3:Statement to be executed if n=case 3;
break;
Default:
//Statement to be executed if n is not equal to all cases;
}
Example (w3schools.com, 2006):
<?php
$fruit = “mango”;
switch ($fruit) {
case “apple”:
echo “My favorite fruit is apple!”;
break;
case “banana”:
echo “ My favorite fruit is banana!”;
break;
case “mango”:
echo “ My favorite fruit is mango!”;
break;
default:
echo “My favorite fruit is not in the list!”;
}
?>
89
Lesson 6: WHILE LOOP Statement
Based on the w3schools.com website (2013), while loops are the simplest type of
loop in PHP. They behave like their C counterparts.
The basic form of a while statement is (w3schools.com, 2013):
while (condition is true) {
//Statement to be executed here...;
}
Example (w3schools.com, 2013):
<?php
$a = 1;
while ($a <=5) {
echo “The number is: $a <br>“;
$a++;
}
?>
Lesson 7: DO...WHILE LOOP statement
Based on the w3schools.com website (2013), do...while loops are very similar to
while loops, except the truth expression is checked at the end of each iteration
instead of in the beginning
do...while statement will always execute the blocked of code once, it will then
checked the condition, and repeat the loop while the condition is true
(w3schools.com, 2019).
Syntax (w3schools.com, 2019):
do {
//Statement to be executed;
} while (condition is true);
90
Example (w3schools.com, 2019):
<?php
$a = 1;
do {
echo “The number is: $a <br>“;
$a++;
}while ($a <=5);
?>
Lesson 8: FOR LOOP Statement
Based on the w3schools.com website (2009), executes block of codes in a specified
number of times.
Basically used when you know the number of times the code loop should run
(w3schools.com, 2009).
Syntax (w3schools.com, 2009):
for (initialization; condition; increment)
{
//statement to be executed
}
Initialization: It is mostly used to set counter (w3schools.com, 2009).
Condition: It is evaluated for each loop iteration (w3schools.com, 2009).
Increment: Mostly used to increment a counter (w3schools.com, 2009).
Example (w3schools.com, 2009):
<?php
for ($a = 1; $a <= 5; $a++) {
echo “The number is: $a <br>“;
}
?>
91
Result (w3schools.com, 2009):
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
Lesson 9: FOREACH LOOP
Based on the w3schools.com website (2019), for each loop works only on arrays,
and is used to loop through each key/value pair in an array.
Syntax (w3schools.com, 2019):
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value
and the array pointer is moved by one, until it reaches the last array element
(w3schools.com, 2019).
Example (w3schools.com, 2019):
<?php
$colors = array(“red”, “green”, “blue”, “yellow”);
foreach ($colors as $value) {
echo “$value <br>“;
}
?>
Result (w3schools.com, 2019):
red green blue yellow
92
Lesson 10: BREAK/CONTINUE
A. PHP Break
a. Based on the w3schools.com website (2020), you have already seen the
break statement used in an earlier chapter of this tutorial. It was used to
“jump out” of a switch statement.
b. The break statement can also be used to jump out of a loop (w3schools.com,
2020).
c. This example jumps out of the loop when x is equal to 4 (w3schools.com,
2020):
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo “The number is: $x <br>“;
}
?>
B. PHP Continue
a. Based on the w3schools.com website (2020), the continue statement breaks
one iteration (in the loop), if a specified condition occurs, and continues with
the next iteration in the loop.
b. This example skips the value of 4 (w3schools.com, 2020):
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo “The number is: $x <br>“;
}
?>
93
C. Break and Continue in While Loop
a. Break
You can also use break and continue in while loops (w3schools.com,
2020):
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo “The number is: $x <br>“;
$x++;
}
?>
b. Continue
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
$x++;
continue;
}
echo “The number is: $x <br>“;
$x++;
}
?>
94
Result (w3schools.com, 2019):
The number is: 0 The number is: 1 The number is: 2 The number is: 3 The number is: 5 The number is: 6 The number is: 7 The number is: 8 The number is: 9
95
Assessment Task
Objectives:
At the end of the exercise, the students should be able to:
use arithmetic operations in writing and executing a PHP program, and
use the if/else, if/else/if/else and switch statements in writing and executing a
PHP program.
Materials:
Computer with the following installed software:
WAMP SERVER 2.5
o Apache
o PHP
Browser
o Google Chrome
o Mozilla Firefox
IDE
o Sublime
o Notepad ++
o Atom
o Visual Studio
Phone with the following installed application:
KSWEB (PRO v3.81)
o Apache (v2.4.28)
o PHP (v7.2.0)
Browser
o Google Chrome
o Mozilla Firefox
AWD – IDE For Web Dev
96
Procedures:
Exercise 1 Using PHP Operators
1. Open your Editor. And key in the codes below:
The above code will perform a simple addition of two variable $x and $y. the sum is
displayed using the echo statement. The result should be 16.
Note: Name your PHP file: operator1[LastName].php
Practical Exercise1 Operators
1. Create a PHP script that will perform the following:
a. Convert Fahrenheit into Celsius and display it as “<Fahrenheit value> degree
Fahrenheit is <Fahrenheit value after conversion> degrees Celsius.”
Tip: Use this formula to convert Fahrenheit into Celsius
°F =
°C + 32
b. Convert Celsius into Fahrenheit and display its output as “<Celsius value>
degree Celsius is <Celsius value after conversion> degree Fahrenheit.”
Tip: Use this formula to convert Fahrenheit into Degrees
°C =
(°F−32)
97
Sample test run:
Fahrenheit: 86
Celsius: 54
Output:
Note: Name your PHP file: operator2[LastName].php
Practical Exercise 2 Control Structures
1. The code below shows a simple use of if/else statement in PHP. Type and test for
your reference.
2. The code above will result “Have a good day!” if the current time is below 18.
Otherwise it will display “Have a good night!”
Note: Name your PHP file: function[LastName].php
98
Summary
Different types of operators are discussed on this module to be able to perform operations
on variables and values, consisting of logical, operational, arithmetic, assignment,
comparison and array operator. Conditional statements are also discussed on this module in
order to perform different actions for different conditions, consisting of if/else, if/else if and
switch. Different type of Loops are also discussed like for, while, do while, and foreach, so
that we know how to repeat code by using loops in PHP on this module.
References
PHP Operators. (2003, September 24). w3schools.com.
https://www.w3schools.com/php/php_operators.asp
PHP if...else...elseif Statements. (2006, April 25). w3schools.com.
https://www.w3schools.com/php/php_if_else.asp
PHP switch Statement. (2006, May 29). w3schools.com.
https://www.w3schools.com/php/php_switch.asp
PHP Loops. (2009, May 14). w3schools.com.
https://www.w3schools.com/php/ php_looping.asp
PHP while Loop. (2013, April 12). w3schools.com.
https://www.w3schools.com/php/php_looping_while.asp
PHP do while Loop. (2019, October 30). w3schools.com.
https://www.w3schools.com/php/php_looping_do_while.asp
PHP for loops. (2009, May 14). w3schools.com.
https://www.w3schools.com/php/php_looping_for.asp
PHP for loops. (2019, October 30). w3schools.com.
https://www.w3schools.com/php/php_looping_foreach.asp
PHP Break and Continue. (2020, June 18). w3schools.com.
https://www.w3schools.com/php/php_looping_break.asp
99
MODULE 6
PHP FUNCTION, ARRAYS
Introduction
In this module, I’ll show you many more things that you can do with function and
arrays. Based on the w3schools.com tutorial (2003), the real power of PHP comes from its
functions. PHP has more than 1000 built-in functions, and in addition you can create your
own custom functions.
Arrays are an example of what has made PHP so popular. Not only do they remove
the tedium of writing code to deal with complicated data structures, they also provide
numerous ways to access data while remaining amazingly fast (Nixon, 2014, pg. 131)
Learning Outcomes
At the end of this lesson, the student should be able to:
1. Appreciate the importance of function and array.
2. Create functions in scripting PHP
3. Create PHP scripts with arrays
100
Lesson 1: Function
Based on the w3schools.com tutorial (2003), self-contained blocked of codes that
perform a specified “function” or task.
executed by a call to the function (w3schools.com, 2003).
can be called anywhere within a page (w3schools.com, 2003).
often accepts one or more parameters (“also referred to as arguments”) which you
can pass to it (w3schools.com, 2003).
Syntax (w3schools.com, 2003):
function functionName()
{
//Statement to be executed;
}
The declaration of a user defined function starts with the word “function” followed by
a short but descriptive name for that function
Example (w3schools.com, 2003):
<?php
function myTeacherName()
{
echo “Bea May M. Belarmino”;
}
myTeacherName();
?>
Result (w3schools.com, 2003):
Bea May M. Belarmino
101
Lesson 2: Function Arguments
Based on the w3schools.com tutorial (2003), function arguments are just like
variables.
specified right after the function name inside the parentheses (w3schools.com,
2003).
Example (w3schools.com, 2003):
<?php
function MyFamName($fname) {
echo “$fname Belarmino.<br>“;
}
MyFamName(“Bea”);
MyFamName(“Yra”);
MyFamName(“Edeliza”);
MyFamName(“Bedo”);
?>
Result (w3schools.com, 2003):
Bea Belarmino.
Yra Belarmino.
Edeliza Belarmino.
Bedo Belarmino.
Lesson 3: Function Returns a Value
Based on the w3schools.com tutorial (2003), function returns a value using the return
statement.
102
Example (w3schools.com, 2003):
<?php
function sum($a, $b) {
$ab = $a + $b;
return $ab;
}
echo “5 + 10 = “ . sum(5, 10) . “<br>“;
echo “7 + 13 = “ . sum(7, 13) . “<br>“;
echo “2 + 4 = “ . sum(2, 4);
?>
Result (w3schools.com, 2003):
5 + 10 = 15
7 + 13 = 20
2 + 4 = 6
Based on the w3schools.com tutorial (2006), Having 3 car names (Honda, Mazda,
and Mitsubishi), how will you store these car names in a variable?
Answer:
o $car1 = “Honda”;
o $car2 = “Mazda”;
o $car3 = “Mitsubishi”;
However, what if you want to loop through the cars and look for a specific one? And
what if you had hundreds or thousands of cars? What will you do?
Answer:
o Create an array and store them to a single variable
Lesson 4: Arrays Types of PHP Arrays
Based on the w3schools.com tutorial (2006), PHP array is a special variable which
allows you to store multiple values in a single variable.
103
Example (w3schools.com, 2006):
$cars = array(“Honda”, “Mazda”, “Mitsubishi”);
The values of an array can be accessed by referring to its index number
(w3schools.com, 2006).
Example (w3schools.com, 2006):
<?php
$cars = array(“Honda”, “Mazda”, “Mitsubishi”);
echo “I have “ . $cars[0] . “, “ . $cars[1] “,” . “, and “ . $cars[2] . “.”;
?>
Result (w3schools.com, 2006):
I have Honda, Mazda, Mitsubishi
Types of PHP Arrays
o Indexed array
o Associative array
o Multidimensional array
A. Indexed Arrays
Indexed arrays or numeric arrays use number as key (w3schools.com, 2006).
The key is the unique identifier, or id of each item within an array
(w3schools.com, 2006).
index number starts at zero (w3schools.com, 2019).
Two ways to create an array:
o Automatic key assignment
$sangre = array(“Amihan”, “Pirena”, “Danaya”, “Alena”);
o Manual key assignment
$sangre [0] = “Amihan”;
$sangre [1] = “Pirena”;
$sangre [2] = “Danaya”;
$sangre [3] = “Alena”;
104
Array COUNT() Function
o The count() function is used to return the length (the number of
elements) of an array (w3schools.com, 2019).
o Example (w3schools.com, 2019):
$sangre = array(“Amihan”, “Pirena”, “Danaya”, “Alena”);
$arrlength=count($sangre);
echo $arrlength;
o Result (w3schools.com, 2019):
4
Array: Displaying Specific Content
o Example (w3schools.com, 2019):
$sangre = array(“Amihan”, “Pirena”, “Danaya”, “Alena”);
echo $sangre[1];
o Result (w3schools.com, 2019):
Pirena
Looping Through Indexed Array
o Loop construct is used to loop through and print all the values of a
numeric array Associative array (w3schools.com, 2019).
o For loop structure is best to use in numeric array (w3schools.com,
2019).
<?php
$sangre = array(“Amihan”, “Pirena”, “Danaya”, “Alena”);
$arrlength = count($sangre);
for ($i= 0; $i< $arrlength; $i++)
{
echo $sangre[$i];
echo “<br>“;}
?>
105
o Result (w3schools.com, 2019):
Amihan
Pirena
Danaya
Alena
B. Associative array
arrays that use named keys as you assigned to them (w3schools.com, 2019).
Associative arrays are similar to numeric arrays but instead of using a
number for the key (w3schools.com, 2019).
it use a value. Then assign another value to the key (w3schools.com, 2019).
Two options to create an associative array
o First:
$sangre = array (“Amihan”=>“Hangin”, “Pirena”=>“Apoy”,
“Danaya”=>“Lupa”, “Alena”=>“Tubig”);
o Second:
$sangre [‘Amihan’] = “Hangin”;
$sangre [‘Pirena’] = “Apoy”;
$sangre [‘Danaya’] = “Lupa”;
$sangre [‘Alena’] = “Tubig”;
Displaying The Content of An Associative Array
o Displaying the content of an associative array is compared with
numeric or indexed array, by referring to its key (w3schools.com,
2019).
o Example (w3schools.com, 2019):
<?php
$sangre = array (“Amihan”=>“Hangin”, “Pirena”=>“Apoy”,
“Danaya”=>“Lupa”, “Alena”=>“Tubig”);
echo “Amihan:” . $sangre [“Amihan”];
?>
106
o Result (w3schools.com, 2006):
Amihan:Hangin
Looping Through An Associative Array
o Loop construct is used to loop through and print all the values of an
associative array (w3schools.com, 2019).
o For each loop structure is best to use in associative array
(w3schools.com, 2019).
o Example (w3schools.com, 2019):
<?php
$sangre = array(“Amihan”, “Pirena”, “Danaya”, “Alena”);
$arrlength= count($sangre);
foreach($sangre as $x => $x_value) {
echo “ID = “ . $x . “, Sangre = “ . $x_value;
echo “<br>“;}
?>
o Result (w3schools.com, 2019):
ID = 0, Sangre = Amihan
ID = 1, Sangre = Pirena
ID = 2, Sangre = Danaya
ID = 3, Sangre = Alena
C. Multidimensional array
an array that contains another array as a value, which in turn can hold
another array as well (w3schools.com, 2019).
This can be done as many times as can be wish –could have an array inside
to create two-or three-dimensional arrays (w3schools.com, 2019).
107
Assuming you have a table like this:
Table 6.1 Multidimensional Table Sample (w3schools.com, 2019)
Name Quantity Sold
Mango 100 96
Apple 60 59
Banana 110 100
Example (w3schools.com, 2019):
<?php
$fruit = array
(
array("Mango",100,96),
array("Apple",60,59),
array("Banana",110,100)
);
?>
echo $fruit[0][0].": QTY: ".$fruit[0][1].", sold: ".$fruit[0][2].".<br>";
echo $fruit[1][0].": QTY: ".$fruit[1][1].", sold: ".$fruit[1][2].".<br>";
echo $fruit[2][0].": QTY: ".$fruit[2][1].",sold:".$fruit[2][2].".<br>";
The two-dimensional array name $fruit array which has two indices: row and
column -contains three arrays. To get access to each specific element of the
$fruit array, one must point to the two indices (w3schools.com, 2019).
Result (w3schools.com, 2019):
Mango: QTY: 100, sold: 96.
Apple: QTY: 60, sold: 59.
Banana: QTY: 110,sold: 100.
108
Using for loop statement to get the element of the $ array
<?php
$sangre = array (
array("Pirena","Hangin",1),
array("Amihan","Apoy",2),
array("Alena","Tubig",3),
array("Danaya","Lupa",4)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$sangre[$row][$col]."</li>";
}
echo "na anak";
echo "</ul>";
}
?>
Result (w3schools.com, 2019):
Row number 0
Pirena
Hangin
1
na anak
Row number 1
Amihan
Apoy
2
na anak
109
Row number 2
Alena
Tubig
3
na anak
Row number 3
Danaya
Lupa
4
na anak
110
Assessment Task
Objectives:
At the end of the exercise, the students should be able to:
use functions in scripting PHP, and
write PHP scripts with arrays
Materials:
Computer with the following installed software:
WAMP SERVER 2.5
o Apache
o PHP
Browser
o Google Chrome
o Mozilla Firefox
IDE
o Sublime
o Notepad ++
o Atom
o Visual Studio
Phone with the following installed application:
KSWEB (PRO v3.81)
o Apache (v2.4.28)
o PHP (v7.2.0)
Browser
o Google Chrome
o Mozilla Firefox
AWD – IDE For Web Dev
111
Procedures:
Exercise 1
1. Create a PHP script that will determine the Chinese Zodiac sign of a particular year.
Below are the 12 Chinese Zodiac signs. Input can be from year 0000 to year 2020.
Note: Use function statement
1. Monkey
2. Rooster
3. Dog
4. Boar
5. Rat
6. Ox
7. Tiger
8. Rabbit
9. Dragon
10. Snake
11. Horse
12. Lamb
Sample input 1: 1986
Output: Tiger
Sample input 2: 2017
Output: Rooster
Note: Name your PHP file: function[LastName].php
2. Create a PHP script using array that will output the following:
array name at index [0] is: apoy
array name at index [1] is: hangin
array name at index [2] is: tubig
array name at index [3] is: lupa
Note: Name your file: array[LastName].php
112
Summary
The real power of PHP comes from its function that’s why; this was also discussed on this
module. Different array types have been also discussed on this module, consisting of
indexed array, associative array, and multi-dimensional array.
References
Nixon, R. (2014, May 19). PHP Array. Learning PHP, MySQL, JavaScript, CSS &
HTML5 (pg.131), United States of America
PHP Functions. (2003, December 16). w3schools.com.
https://www.w3schools.com/php/php/php_functions.asp
PHP Arrays. (2006, May 1). w3schools.com.
https://www.w3schools.com/php/php_arrays.asp
PHP Indexed Arrays. (2019, October 19). w3schools.com.
https://www.w3schools.com/php/php_arrays_indexed.asp
PHP Associative Arrays. (2019, October 19). w3schools.com.
https://www.w3schools.com/php/php_arrays_associative.asp
PHP Multidimensional Arrays. (2013, February 5). w3schools.com.
https://www.w3schools.com/php/php_arrays_multidimensional.asp
113
MODULE 7
PHP FORMS
Introduction
With your solid foundation in both PHP and JavaScript, it’s time to bring these
technologies together to create web forms that are as user-friendly as possible. We’ll be
using PHP to create the forms and JavaScript to perform client-side validation to ensure that
the data is as complete and correct as it can be before it is submitted. Final validation of the
input will then be made by PHP, which will, if necessary, present the form again to the user
for further modification.
In the process, this module will cover validation in PHP.
Learning Outcomes
At the end of this lesson, the student should be able to:
1. Understand get, post & validation
2. Appreciate the importance of web forms security.
3. Create web forms using HTML, CSS, and PHP scripts.
114
Lesson 1: Get and Post Method
Based on the w3schools.com tutorial (2013), a form data can be submitted using
POST and GET method (w3schools, 2013).
Both are used for same purpose but stand apart for some specifications (w3schools,
2013).
GET and POST create an array which holds key/value pairs, where keys are the
name of the form controls and values are the input data by the use (w3schools,
2013).
Both GET and POST method are treated as $_GET and $_POST in PHP
(w3schools, 2013).
These methods are super globals, which means that they are always accessible, and
they can be accessed using any function, class or file (w3schools, 2013).
The $_GET method is an associative array of variables passed to the current script
via the URL parameters (w3schools, 2013).
The $_POST method is an array of variables passed to the current script via the
HTTP POST method (w3schools, 2013).
In this method the information is transferred in a hidden manner (w3schools, 2003).
A form that submits information is appended to the URL in the form of Query String
which consists of name = value pairs in URL known as URL Encoding (w3schools,
2013).
This string contains user values/data, which are joined using equal (=) signs,
separated by ampersand (&), and spaces are removed and replaced with plus (+)
sign (w3schools, 2013).
Sample URL Syntax:
Name1=value1&name2=value2&name3=value3
Sample URL Output:
http:/.www.example.com/[email protected]&contact=09176543210
115
Lesson 2: Get Method
Based on the w3schools.com tutorial (2013), The code below is a client-side HTML
form using method = “get ”for user to fill the information (w3schools, 2003).
Example (w3schools.com, 2013):
<form action="#" method="get">
<input type="text" name="name" placeholder="Your Name"></input><br/>
<input type="text" name="email" placeholder="Your Email"></input><br/>
<input type="text" name="contact" placeholder="Your Mobile"></input><br/>
<input type="submit" name="submit" value="Submit"></input>
</form>
The code below is the server-side PHP script where, $_GET associative array is
used to receive sent information from server end (w3schools, 2013).
<?php
if( $_GET["name"] || $_GET["email"] || $_GET["contact"])
{
echo "Welcome: ". $_GET['name']. "<br/>";
echo "Your Email is: ". $_GET["email"]. "<br/>";
echo "Your Mobile No. is: ". $_GET["contact"];
}
?>
Lesson 3: Post Method
Sample Syntax (w3schools.com, 2013):
<form action="#" method="post">....</form>
116
Based on the w3schools.com tutorial (2013), below is a server-side PHP script
where $_POST associative array is used to receive sent information at server end
<?phpif( $_POST["name"] || $_POST["email"] || $_POST["contact"])
{
echo "Welcome: ". $_POST['name']. "<br/>";
echo "Your Email is: ". $_POST["email"]. "<br/>";
echo "Your Mobile No. is: ". $_POST["contact"];
}
?>
Lesson 4: Form Validation
Figure 7.1 PHP Form Validation Example
Source: w3schools.com tutorial (2013)
Based on the w3schools.com tutorial (2013), The form they provided shown in Figure
7.1 consists of the following elements:
o Name (required field -must contain letters and whitespaces)
o E-mail (required field -must contain valid email address)
o Website (optional field -if present, must contain valid website URL)
117
o Comments (optional field -a multi-line text field)
o Gender (required field -must select a radio button)
A. Form Elements
a. Text Field Elements
The Name, E-mail, Website are input elements (w3schools.com, 2013).
Input elements, in particular, used text and submit values for its types
attribute in order to create text fields and buttons
The HTML code for Text Field (w3schools.com, 2013)
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
b. Radio button Elements
Radio button shows several options to the users from which the user may
select one (w3schools, 2013).
HTML code for Radio Button (w3schools, 2013):
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
c. Text Area Elements
The text area is typically a large text field with multiple rows (w3schools,
2013).
The text area element has three attributes –name, rows, and cols attribute
HTML code for Text Area (w3schools, 2013):
Comment: <textareaname="comment" rows="8" cols="80">Type your
comments here...</textarea>
d. Select Elements
list element offers options from which the user might choose. A list can be
created using the select element, within which is nested option elements
for each option to appear (w3schools, 2013).
118
The select element has a name attribute giving the name for the browser
to use when identifying the selection when the form is submitted
(w3schools, 2013).
The option element has a value attribute for specifying what value to send
when that option is selected, and it has a select attribute which allows the
HTML to specify which option is initially selected (w3schools, 2003).
HTML code for Select (w3schools, 2013):
Country: <select name="country">
<option value="php" selected="selected">Afghanistan</option>
<option value="albania">Albania</option>
<option value="algeria">Algeria</option>
</select>
e. Form Element
The HTML code of the form element (w3schools, 2013):
<form method="post" action="<?phpecho
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
when the form is submitted, the form data is sent with method=”post”
(w3schools, 2013).
So, the $_SERVER["PHP_SELF"] sends the submitted forms data to the
page itself, instead of jumping to a different page (w3schools, 2013).
The $_SERVER["PHP_SELF"]is a super global variable that returns the
filename of the currently executing script (w3schools, 2013).
Htmlspecialchars()function converts special characters to HTML entities
Cross-site scripting (XSS) is a type of computer security vulnerability
typically found in Web application (w3schools, 2013).
Example: test_form.php
<form method="post" action="<?phpecho $_SERVER["PHP_SELF"];?>">
if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be
translated to (w3schools, 2013):
119
<form method="post" action="test_form.php">
consider that if a user enters the following URL in the address bar
(w3schools, 2013):
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hac
ked')%3C/script%3E
will be translated (w3schools, 2013):
<form method="post"
action="test_form.php/"><script>alert('hacked')</script>
o Be aware that any JavaScript code can be added inside the
<script>tag (w3schools, 2013).
o A hacker can redirect the user to a file on another server, and that
file can hold malicious code that can alter the global variables or
submit the form to another address to save the user’s data
(w3schools, 2013).
B. How To Avoid $_SERVER[“PHP_SELF”] Exploit?
The $_SERVER[“PHP_SELF”] exploit can be avoided using the
htmlspecialchars() function (w3schools, 2013).
If the user tries to exploit the PHP_SELF variable, it will result (w3schools,
2013):
<form method="post"
action="test_form.php/"><script>alert('hacked')</script>">
C. Validate Form Data With PHP
The very first thing to do to validate form data with PHP is to pass all
variables through PHP’s htmlspecialchars() function (w3schools, 2003).
For example (w3schools, 2013):
<script>location.href('http://www.hacked.com')</script>
With htmlspecialchars() function it would not be executed, because it would
be saved as HTML escaped code like this (w3schools, 2013):
<script>location.href('http://www.hacked.com')</script>
120
test_input()
<?php
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Lesson 5: Form Required Fields
Based on the w3schools.com tutorial (2013), in the previous slide, all input fields
were optional, meaning no required fields to be filled in by the user.
121
Here is a simple PHP script that checks the name for empty input and throws an
error message if the input is empty (w3schools, 2013):
if (empty($_POST["name"]))
{
$nameErr= "Please enter your name";
}
else
{
$name = test_input($_POST["name"]);
}
To display the error message in the HTML form (this will be generated if the user
tries to submit the form without filling in the required fields) use the code below
(w3schools, 2013):
Name: <input type="text" name="name">
<span class="error">* <?phpecho $nameErr;?></span>
Lesson 6: Form URL/E-mail
A. PHP - Validate Name
The code below shows a simple way to check if the name field only contains letters,
dashes, apostrophes and whitespaces. If the value of the name field is not valid, then
store an error message (w3schools, 2013):
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
B. PHP - Validate E-mail
The easiest and safest way to check whether an email address is well-formed is to
use PHP's filter_var() function. In the code below, if the e-mail address is not well-
formed, then store an error message (w3schools, 2013):
122
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
C. PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular
expression also allows dashes in the URL). If the URL address syntax is not valid,
then store an error message (w3schools, 2013):
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
Complete set of code are given below (w3schools, 2013):
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
123
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
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";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
124
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br>
<br>
125
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
126
Lesson 7: Form Complete
To show the values in the input fields after the user hits the submit button, we add a
little PHP script inside the value attribute of the following input fields: name, email,
and website. In the comment textarea field, we put the script between the <textarea>
and </textarea> tags. The little script outputs the value of the $name, $email,
$website, and $comment variables (w3schools, 2013).
Then, we also need to show which radio button that was checked. For this, we must
manipulate the checked attribute (not the value attribute for radio buttons)
(w3schools, 2013):
Name: <input type="text" name="name" value="<?php echo $name;?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
Website: <input type="text" name="website" value="<?php echo $website;?>">
Comment: <textarea name="comment" rows="5" cols="40"><?php echo
$comment;?></textarea>
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
127
Assessment Task
Objectives:
At the end of the exercise, the students should be able to:
create web forms using HTML, CSS, and PHP scripts.
Materials:
Materials:
Computer with the following installed software:
WAMP SERVER 2.5
o Apache
o PHP
Browser
o Google Chrome
o Mozilla Firefox
IDE
o Sublime
o Notepad ++
o Atom
o Visual Studio
Phone with the following installed application:
KSWEB (PRO v3.81)
o Apache (v2.4.28)
o PHP (v7.2.0)
Browser
o Google Chrome
o Mozilla Firefox
AWD – IDE For Web Dev
128
Procedures:
Exercise 1 - Creating a Form
In this exercise, a PHP script will be created for a simple web form that will accept data from
user inputs. The form will include common fields like name, address, and phone
number. And form elements such as radio button, checkbox, textarea, and option button.
Few HTML and CSS will also be applied for the design.
1. Open the Editor and type the following codes:
<!DOCTYPE html>
<html>
<head>
<title>Cake Form</title>
</head>
<body>
</body>
</html>
2. Save the file as cakeform[LastName].php under the WAMP -> www folder in
local drive.
3. To test the script, open any of the installed browser and type
localhost/cakeform[Surname].php in the address bar .If error occurs, check if
the WampServer is in active mode. Otherwise, start the WampServer and wait
until the icon in the app tray becomes green. Test the script again.
4. Open the cakeform[Your Surname].php in Notepad and key in the following
codes inside the <body>tag:
<body>
<h1>Make Your Own Cake! </h1>
<h4>Select Size for the Cake: </h4>
<input type="radio" name="SelectedCake" value = "Round6"> Round cake 6" -serves 8
people <br/>
<input type="radio" name="SelectedCake" value = "Round8"> Round cake 8" -serves 12
people <br/>
</body>
129
5. Save and test your script.
6. Add these to the options above:
Round cake 10" -serves 16 people
Round cake 12" -serves 30 people
7. The page should look like in the figure below, after the script is finished
8. Next, add a dropdown element for the cake’s flavor. Type the following codes
below:
<h4>Select a Cake Flavor: </h4>
<select name="Cake Flavor">
<option value="Flavor" selected="selected">Select Flavor</option>
<option value="Carrot">Carrot</option>
<option value="Chocolate">Chocolate</option>
<option value="Banana">Banana</option>
</select>
9. Continue the coding by adding the following cake’s flavor in the dropdown
element:
Red Velvet
Strawberry
Vanilla
Combo
130
10. When the script is finished, it should look like this:
11. Add a checkbox element which will hold the fillings for the cake. Use the codes
below.
<h4>Select Fillings:</h4>
<label><input type="checkbox" value="Cream" name='Filling[]' />Cream</label><br>
<label><input type="checkbox" value="Fudge" name='Filling[]' />Fudge</label><br>
<label><input type="checkbox" value="Ganache" name='Filling[]' />Ganache</label><br>
<label><input type="checkbox" value="Hazelnut" name='Filling[]' />Hazelnut</label><br>
<label><input type="checkbox" value="Mousse" name='Filling[]' />Mousse</label><br>
<label><input type="checkbox" value="Pudding" name='Filling[]' />Pudding</label><br>
12. Save and test your script.
131
13. Try to fix your script to achieve the result on the next page. The form should look
like this:
14. Save your file.
15. Add the following contact details to complete the form.
Name
Address
Phone numbe
16. Use this code:
Name: <input type="text" name="name">
17. Then add a submit button to the form. Use the following code:
<input type='submit' name='submitted' id='submit' value='Submit' />
132
18. Try to fix your script to achieve the result below:
Exercise 2 Applying CSS
The <div>...</div> element gives structure and context to any block-level content in the
document.
1. Open your cakeform.php.
2. Below the <title>...</title> tag, place the code below:
<link href="cakeform.css" rel="stylesheet" type="text/css" />
This code links to cakeform.css file.
3. Insert the <div id=”wrap”> after the <body> tag and </div> before the </body> tag
at the end of the script. See figure below:
133
4. After the <div id=”wrap”>, insert <div> and its closing pair before the </div>
element at the bottom part of the script. See figure below:
5. Next, put another division to wrap the order of each container. Type the <div
class= ”cont_order”> and its closing pair </div> after the <div>. See figure below
for your reference.
6. Save your file and try to test your script. Observe that there is always a closing
tag pair for every tag.
7. Now, separate each form element with the <div class='field_container'> and its
closing pair </div>.Refer to the figure below for your reference.
8. On your own, apply <div class= 'field_container'> to Select a Cake a Cake Flavor
and Select Fillings.
134
9. Update the Contact Details area using the codes below:
10. Save and test your script.
11. To make the form more structural and organized, let’s put a <fieldset> element to
our container. <fieldset> element is a structural container for form elements (as
distinguished from the functional containment of the form element).To do this,
type <fieldset> below the <div class="cont_order">and its closing tag </fieldset>
after the closing tag of <div class="cont_order">
12. Also change the <h1> Make Your Own Cake! </h1> to <legend> Make Your
Own Cake!</legend>.The<legend> element acts as a label for a fieldset element.
13. Do this also in the contact details part.
135
14. Save and test your code. The web form should look like the screenshot on the
next page after the script is finished.
136
Summary
Final validation of the input was made by PHP, which will, is very necessary, in presenting
the form to the end user for further modification. That is why form validation, form required
fields was also discussed on this course.
References
Nixon, R. (2014, May 19). JavaScript and PHP Validation and Error Handling.
Learning PHP, MySQL, JavaScript, CSS & HTML5 (pg. 381), United States of
America
PHP Form Handling. (2003, September 25). w3schools.com
https://www.w3schools.com/php/php_forms.asp
PHP Form Validation. (2013, September 12). w3schools.com
https://www.w3schools.com/php/php_form_validation.asp
PHP Forms Required Fields. (2013, September 12). w3schools.com
https://www.w3schools.com/php/php_form_required.asp
PHP Forms Validate E-mail and URL. (2013, September 14). w3schools.com
https://www.w3schools.com/php/php_form_url_email.asp
PHP Complete Form Example. (2013, September 14). w3schools.com
https://www.w3schools.com/php/php_form_complete.asp
137
MODULE 8
PHP COOKIES AND SESSION
Introduction
A cookie is an item of data that a web server saves to your computer’s hard disk via
a web browser. It can contain almost any alphanumeric information (as long as it’s under4
KB) and can be retrieved from your computer and returned to the server. Common uses
include session tracking, maintaining data across multiple visits, holding shopping cart
contents, storing login details, and more (Nixon, 2014, pg. 301)
Because your program can’t tell what variables were set in other programs—
or even what values the same program set the previous time it ran—you’ll sometimes want
to track what your users are doing from one web page to another. You can do this by setting
hidden fields in a form and checking the value of the fields after the form is submitted, but
PHP provides a much more powerful and simpler solution in the form of sessions. (Nixon,
2014, pg. 312)
Learning Outcomes
At the end of this lesson, the student should be able to:
1. Understand the cookies and sessions
2. Appreciate the importance of cookies and sessions
3. Apply the cookies and sessions in creating web form.
138
Lesson 1: Cookie
Based on the w3schools.com tutorial (2003), small text file which store a small
amount of data that the server embeds on the user’s local machine
often used to identify a user (w3schools.com, 2003).
setcookie() function is used to create a cookie (w3schools.com, 2003).
Syntax (w3schools.com, 2003):
<?php
setcookie(name, value, expire, path, domain, secure, httponly);
?>
The table below shows the cookie parameter (w3schools.com, 2003):
Table 8.1 Cookie Parameter (w3schools.com, 2003)
Parameter Description
Name The name of the cookie
Value The value of the cookie
Expire The expiration date. The default value is zero
Path The path on the server for which the cookie will be
available
Domain The domain for which the cookie is available to
Secure This field if present, indicates that the cookie should be
sent only if a secure HTTPS connection exist
HTTPONLY This signifies that when true the cookie will be made
accessible through the HTTP protocol
Example (w3schools.com, 2003):
<?php setcookie("username", "John doe", time()+30*24*60*60); ?>
Or
<?php
$cookie_name= "username";
$cookie_value= "John Doe";
setcookie($cookie_name, $cookie_value, time()+(86400 * 30), "/");
?>
139
Lesson 2: Accessing Cookie Value
Based on the w3schools.com tutorial (2003), The $_COOKIE super global variable
Example (w3schools.com, 2003):
<?php
echo $_COOKIE ["username"];
?>
The PHP isset() function (w3schools.com, 2003):
<?php
if (isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else {
echo "Welcome guest!";}
?>
Lesson 3: Deleting A Cookie
Based on the w3schools.com tutorial (2003),
<?php
setcookie("username", "", time()-3600);
?>
Lesson 4: Sessions
Based on the w3schools.com tutorial (2006), a way to store certain data to be used
across multiple pages.
Stored on the server on a temporary basis (w3schools.com, 2003).
Unlike a PHP cookie the information is not stored on the user’s local machine
(w3schools.com, 2003).
A session creates a file in a temporary directory on the server where registered
session variables and their values are stored (w3schools.com, 2003).
140
Lesson 5: Starting A PHP Session
Based on the w3schools.com tutorial (2006), the session_start() function:
<?php
session_start();?>
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Example (w3schools.com, 2003):
<?phpsession_start();?>
<!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["firstname"] = "Kylie Nicole";
$_SESSION["middlename"] = "Padilla";
$_SESSION["lastname"] = "Abrenica";
echo "Session variables are set.";
?>
</body>
</html>
Lesson 6: Accessing Session Data
Based on the w3schools.com tutorial (2006), call the session_start() function and
then pass the corresponding key to the $_SESSION associative array.
141
Example (w3schools.com, 2003):
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo 'Hi, ' . $_SESSION["firstname"] . '' . $_SESSION["lastname"];
?>
</body>
</html>
Lesson 7: Destroying A Session
Based on the w3schools.com tutorial (2006), remove all certain global session data,
simply unset or destroy the corresponding key of the $_SESSION using
session_unset() function and session_destroy().
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
session_unset();
session_destroy();
?>
</body>
</html>
142
Assessment Task
Objectives:
At the end of the exercise, the students should be able to:
apply form validation.
Materials:
Computer with the following installed software:
WAMP SERVER 2.5
o Apache
o PHP
Browser
o Google Chrome
o Mozilla Firefox
IDE
o Sublime
o Notepad ++
o Atom
o Visual Studio
Phone with the following installed application:
KSWEB (PRO v3.81)
o Apache (v2.4.28)
o PHP (v7.2.0)
Browser
o Google Chrome
o Mozilla Firefox
AWD – IDE For Web Dev
Procedures:
Exercise 1 Applying Form Validation
Take a look at your previous form shown in next page. The purpose of the form is to capture
the details which the user supplied to the form using the different form elements
(radio button, check box, text area, etc.). These inputs will be validated to ensure the
validity of the inputted details by the user, for example, the user has entered their contact
information and the name was left blank.
143
1. Now, open your cakeform[Surname].php file using any text editor.
144
2. Type the following codes above <!DOCTYPE html> tag.
In PHP all variables to be used must be defined first with the $ sign and initialized
them with empty values. The name of the variable should be identical to
its function or purpose. E.g. $select_cake_error will be called if no cake were
selected.
3. Type the following codes below the defined variables, before the PHP closing tag
(?>). This will be executed when the form is submitted.
4. Navigate to <div class='field_container'> below type the following code:
5. Below the submit button type the following code:
145
6. Navigate to <div class="cont_details"> and update your code after <input> tag with
the following format:
This code checks for the inputted name of the user, if the name field is empty the
form will prompt “Name is empty. Please enter your name.”
7. Now, validate if the user select a size for the cake. Enter the following code above
the <!DOCTYPE html> tag, after the first validation code.
8. Go to <div class='field_container'> which specifies the size of the cake and update
your code with the code below:
146
9. When you submit the form using the Submit button, the output should look like the
figure below.
147
Summary
A cookie is an item of data that a web server saves to your computer’s hard disk via
a web browser. It can contain almost any alphanumeric information (as long as it’s under4
KB) and can be retrieved from your computer and returned to the server (Nixon, 2014, pg.
301).
Because your program can’t tell what variables were set in other programs—
or even what values the same program set the previous time it ran—you’ll sometimes want
to track what your users are doing from one web page to another. You can do this by setting
hidden fields in a form and checking the value of the fields after the form is submitted, but
PHP provides a much more powerful and simpler solution in the form of sessions. (Nixon,
2014, pg. 312)
References
Nixon, R. (2014, May 19). Using Cookies in PHP. Learning PHP, MySQL,
JavaScript, CSS & HTML5 (pg. 301), United States of America
Nixon, R. (2014, May 19). Using Sessions. Learning PHP, MySQL, JavaScript, CSS
& HTML5 (pg. 312), United States of America
PHP Cookies. (2003, February 25). w3schools.com
https://www.w3schools.com/php/php_cookies.asp
PHP Sessions. (2006, July 13). w3schools.com
https://www.w3schools.com/php/php_sessions.asp
*END OF MODULE FOR MIDTERM PERIOD
THERE WILL BE MIDTERM EXAMINATION ON NOVEMBER 19 TO 21, 2020,
PLESE SEE YOUR SPECIFIC SCHEDULE FOR THIS COURSE. THANK YOU