0% found this document useful (0 votes)
5 views

HTML Forms and Server Side Scripting - PHP

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

HTML Forms and Server Side Scripting - PHP

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

1

Chapter Two
HTML FORMS AND SERVER
SIDE SCRIPTING

5/18/2024
By:- Abreham G.
Using Operators
2

 PHP supports many operators.

Mathematical Operators
 Arithmetic operators are straightforward—they are just the
normal mathematical operators.
Operator Description
+ Adds two numbers together.
- Subtracts the second number from the first number.
* Multiplies two numbers together.

/ Divides the first number by the second number.


% Finds the remainder when the first number is divided by the
second number.
5/18/2024
Using Operators…
3

 Example: a program that performs all mathematical operation


on two numbers
$a = 10;
$b = 20;
$c = $a + $b; //result: 30
$c = $a - $b; //result: -10
$c = $a * $b; //result: 200
$c = $a / $b; //result: 0.5
$c = $a % $b; //result: 10

5/18/2024
Using Operators…
4

 You should note that arithmetic operators are usually applied to


integers or doubles.
 If you apply them to strings, PHP will try and convert the string to a
number.

 If it contains an “e” or an “E”, it will be converted to a double;


otherwise it will be converted to an int.

5/18/2024
Using Operators…
5

Pre- and Post-Increment and Decrement operators

operator description example meaning

++ postfix increment $x++ $x = $x+1

-- postfix decrement $x-- $x = $x-1

++ prefix increment ++$x $x = $x+1

-- prefix decrement --$x $x = $x-1

Example: a program that performs postfix and prefix operations


$a = 4;
echo “<br>”, ++$a;
$b = 10;
echo “<br>”, $b++;
echo “<br>”, $b; 5/18/2024
Using Operators…
6

 All the increment operators have two effects—they increment and assign a value.
$a=4;
echo ++$a;
 The second line uses the prefix increment operator.
 First, $a incremented by 1, and second, returns the incremented value.
 In this case, $a is incremented to 5 and then the value 5 is returned and printed.

 However, if the ++ is after the $a, we are using the postfix increment operator.
 This has a different effect.
$a=4;
echo $a++;

 In this case, first, the value of $a is returned and printed, and second, it is
incremented.
 The value that is printed is 4.
 However, the value of $a after this statement is executed is 5.
5/18/2024
Using Operators…
7

Operator description example meaning


+= add and assign $x += 5 $x = $x + 5
-= subtract and assign $x -= 5 $x = $x – 5
/= divide and assign $x /= 5 $x = $x / 5
*= multiply and assign $x *= 5 $x = $x * 5
%= modulate and assign $x %= 5 $x = $x % 5
.= concatenate and assign $x .= " test" $x = $x." test"

5/18/2024
Using Operators…
8

Comparison operators
 The comparison operators are used to compare two values.
 Expressions using these operators return either true or false
operator name description
== equal True if its arguments are equal to each other, false otherwise
!= not equal False if its arguments are equal to each other, true otherwise
< less than True if the left-hand argument is less than its right-hand argument, but false
otherwise
> greater than True if the left-hand argument is greater than its right-hand argument, but
false otherwise
<= less or equal True if the left-hand argument is less than its right-hand argument or equal to
it, but false otherwise
>= greater or equal True if the left-hand argument is greater than its right- hand argument or
equal to it, but false otherwise
=== identical True if its arguments are equal to each other and of the same type, but false
5/18/2024
otherwise
Using Operators…
9

 Example:
<?php
$var = "30";
$num = 30;
if($var == $num)
print "They are equal.<br>";
if($var === $num)
print "They are equal and same data type.<br>";
$var = (int) “30”;
if($var === $num)
print "2. They are equal and same data type.<br>";
?>
Output:
They are equal
5/18/2024
2. They are equal and same data type.
Using Operators…
10

Logical Operators
 The logical operators are used to combine the results of logical
conditions.
 For example, we might be interested in a case where the value
of a variable is between 0 and 100.
 We would need to test the conditions $a >= 0 and $a <=
100, using the AND operator, as follows:
if($a >= 0 && $a <=100)

5/18/2024
Using Operators…
11

operator description

and Is true if and only if both of its arguments are true

or Is true if either (or both) of its arguments are true.

xor Is true if either (but not both) of its arguments are true

! Is true if its single argument (to the right) is false and false if its argument is true

&& Same as and, but binds to its arguments more tightly

|| Same as or but binds to its arguments more tightly

5/18/2024
Using Operators…
12

The ternary operator


 It plays a role somewhere between a Boolean operator and a true

branching construct.
 Its job is to take three expressions and use the truth value of the first
expression to decide which of the other two expressions to return.
 The syntax looks like:
test-expression ? yes-expression : no-expression

 The value of this expression is the result of yes-expression if test-


expression is true; otherwise, it returns no-expression.
 For example, assigning to $max either $first or $second, whichever
is larger:
$max_num = $first > $second ? $first : $second;
5/18/2024
Conditional Statements
13

if Statements
 We can use an if statement to make a decision.

 You should give the if statement a condition that is evaluated to true or false.

 If the condition is true, the associated block of code will be executed.

 Conditions in if statements must be surrounded by brackets ().

 The syntax of if statement:


if(condition) {
statements;
}

 Example: an if statement that checks if a variable value is less than 50 (student


failed course)
if($mark<50){
print(“You have to improve your mark”);
}
5/18/2024
Conditional Statements…
14
if..else statements
 An else statement allows you to define an alternative action to be taken when the condition in
an if statement is false.
 This allows to take one action when the condition is true and another action when the condition
is false.

 The syntax of if statement:


if(condition) {
statements;
}
else {
statements;
}
 Example:
if($mark<50) {
print(“You failed this course”);
}
else{
print(“You have passed the course”);
} 5/18/2024
Conditional Statements…
15

else if Statements
 For many of the decisions we make, there are more than two options.

 We can create a sequence of many options using the else if statement.

 By providing a sequence of conditions, the program can check each until it finds one
that is true.

 Example: a program that checks if a variable value is between 1 and 5 and


display message accordingly
if ($day == 5)
print(“Five golden rings<BR>”);
elseif ($day == 4)
print(“Four calling birds<BR>”);
elseif ($day == 3)
print(“Three French hens<BR>”);
elseif ($day == 2)
print(“Two turtledoves<BR>”);
elseif ($day == 1)
5/18/2024
print(“A partridge in a pear tree<BR>”);
Conditional Statements…
16

switch statements
 The switch statement works in a similar way to the if
statement
 You need to provide a case statement to handle each
value you want to react to and, optionally, a default
case to handle any that you do not provide a specific
case statement.

5/18/2024
Conditional Statements…
17

switch (expression) {
case result1:
//execute this if expression results in result1
break;
case result2:
//execute this if expression results in result2
break;
default:
//execute this if no break statement
//has been encountered
}

 The expression used in a switch statement is often just a variable.


 Within the switch statement's block of code, you find a number of case statements.
 Each of these cases tests a value against the result of the switch expression.
 If the case is equivalent to the expression result, the code after the case statement is
executed. 5/18/2024
Conditional Statements…
18

 The break statement ends the execution of the switch statement


altogether.
 If the break statement is left out, the next case statement is
executed.
 If the optional default statement is reached, its code is
executed.
 It is important to include a break statement at the end of any
code that will be executed as part of a case statement.
 Without a break statement, the program flow will continue to
the next case statement and ultimately to the default
statement.
 In most cases, this will result in unexpected behavior,
5/18/2024
likely
incorrect!
Example: switch statement that checks the mood of the person
<?php
$mood = “happy";
19
switch ($mood)
{
case "happy":
echo "Hooray, I'm in a good mood";
break;
case "sad":
echo "Awww. Don't be down!";
break;
default:
print "Neither happy nor sad but $mood";
break;
}
?>

5/18/2024
Using Loops
20

 Loop statements are designed to enable you to achieve repetitive


tasks.
 A loop will continue to operate until a condition is achieved, or you
explicitly choose to exit the loop.
 For example, a loop that echoes the names of all the files in a
directory needs to repeat until it runs out of files.

 There are three types of loops:


 for loop: Sets up a counter; repeats a block of statements until the
counter reaches a specified number
 while loop: Sets up a condition; checks the condition, and if it’s true,
repeats a block of statements until the condition becomes false
 do..while loop: Sets up a condition; executes a block of statements;
checks the condition; if the condition is true, repeats the block of
statements until the condition becomes false
5/18/2024
Using Loops…
21

for loop
 The most basic for loops are based on a counter.

 You set the beginning value for the counter, set the ending value, and
set how the counter is incremented/decremented.
 The general format is as follows:

for (startingvalue; endingcondition; increment)


{
block of statements;
}

 Example:
for ($i = 1; $i <= 3; $i++) {
echo “$i. Hello World!<br>”;
}
5/18/2024
You can nest for loops inside of for loops.
Excersice
22

Write a php program for the following table

1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81

5/18/2024
Using Loops…
23

while loop
 One of PHP looping construct is while, which has the following syntax:

while (condition)
{
statement
}

 The while loop evaluates the condition expression as a Boolean


 If it is true, it executes statement and then starts again.
 If the condition is false, the while loop terminates.
 The body of a while loop may not execute even once, as in:
$count = 1;
while ($count <= 10)
{
print(“count is $count<BR>”);
$count = $count + 1;
} 5/18/2024
Using Loops…
24

do..while loop
 Like a while loop, a do..while loop continues repeating as long
as certain conditions are true.
 Unlike while loops, the conditions are tested at the bottom of
the loop.
 If the condition is true, the loop repeats.

 When the condition is not true, the loop stops.

 The general format for a do..while loop is as follows:


do
{
block of statements
} while (condition);
5/18/2024
Using Loops…
25

 Example: a loop that displays numbers from 1 to 10


$count = 1;
do
{
print(“count is $count<BR>”);
$count = $count + 1;
}while ($count <= 10);

Avoiding infinite loops


 You can easily set up loops that never stops i.e. which repeats
forever.
 These are called infinite loops and it is usually a mistake in the
programming.
 This is very stressful on your Web server, and renders the Web page
in question unusable. 5/18/2024
Using Loops…
26

Breaking out of a loop


 Sometimes you want your script to break out of a loop.

 PHP provides two statements for this purpose:

 break: breaks completely out of a loop and continues with


the script statements after the loop.
 continue: stops current iteration and goes back to condition
check. If condition check is true, it will go to the next
iteration.

 The break and continue statements are usually used in


conditional statements.
 In particular, break is used most often in switch statements.
5/18/2024
Using Loops…
27

Example: break statement


$counter = 0;
while ( $counter < 5 ) {
$counter++;
if ( $counter == 3 ) {
echo “break\n”;
break;
}
echo “Last line in loop: counter=$counter\n”;
}
echo “First line after loop\n\n”;

The output of this statement is the following:


Last line in loop: counter=1
Last line in loop: counter=2
break
5/18/2024
First line after loop
Using Loops…
28

Exercise
1. Write a while loop that displays prime numbers
between 1 and 100
2. Write a for loop that displays the squared and
cubed value of numbers between 0 and 100.
3. Write a do while loop that calculates the factorial
of a number.
4. Write a loop that gets the factors of a given
number.

5/18/2024
Array
29

 Is a variable that can store more than one value.


 the array() function is used to create an array.
 indexed arrays
 There are two ways to create indexed arrays.
 $cars = array("Volvo", "BMW", "Toyota");
Or
 $cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota"
 Associative Arrays
 Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
 $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Or
 $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

5/18/2024
Creating Array
30

 There are two ways


 Informally
 you can create the array simply by making reference to it.
 $state[0] = "Delaware";

 Formally
 Uses the array() function
 array array([item1 [,item2 ... [,itemN]]])
 $languages = array ("English", "Gaelic", "Spanish");
 $languages = array ("Spain" => "Spanish","Ireland" =>
"Gaelic", "United States" => "English");

5/18/2024
Cont.……
31

 range()
 The range() function provides an easy way to quickly create
and fill an array consisting of a range of low and high
integer values.
 $die = range(0,6);
 Same as specifying $die = array(0,1,2,3,4,5,6)
 The optional step parameter offers a convenient means for
determining the increment between members of the range.
 $even = range(0,20,2);
 also be used for character sequences
 $letters = range("A","F");

5/18/2024
Outputting Array
32

 Using index or Key.


 print_r()
 Testing Array
 is_array() is used to check if a given variable is an
array or not.
 boolean is_array(mixed variable)

 Returns true if the variable is array and false if it is not.

5/18/2024
Adding and Removing array elements
33

 PHP provides a number of functions for both growing


and shrinking an array.
 array_push()
 The array_push() function adds variable onto the end of the
target_array.
 $states = array("Ohio","New York");
 array_push($states,"California","Texas");
 array_pop()
 The array_pop() function returns the last element from
target_array.
 $states = array("Ohio","New York","California","Texas");
 $state = array_pop($states); // $state = "Texas"

5/18/2024
Cont.…..
34

 array_shift()
 The array_shift() function is similar to array_pop(), except
that it returns the first array item found on the target_array
rather than the last.
 $states = array("Ohio","New York","California","Texas");
 $state = array_shift($states);
 array_unshift()
 The array_unshift() function is similar to array_push(), except
that it adds elements to the front of the array rather than to
the end.
 $states = array("Ohio","New York");
 array_unshift($states,"California","Texas");

5/18/2024
Cont.….
35

 array_pad()
 The array_pad() function modifies the target array,
increasing its size to the length specified by length.
 $states = array("Alaska","Hawaii");
 $states = array_pad($states,4,"New colony?");

5/18/2024
Locating array elements
36

 Array_keys()
 returns an array consisting of all keys located in the
array target_array.
 E.g show the keys using print_r()

 array_key_exists()
 boolean array_key_exists(mixed key, array
target_array).
 returns TRUE if the supplied key is found in the array
target_array, and returns FALSE otherwise.

5/18/2024
Cont.….
37

 array_values()
 The array_values() function returns all values located in the array
target_array, automatically providing numeric indexes for the
returned array.
 array_search()
 searches the array haystack for the value needle, returning its
key if located, and FALSE otherwise.
 mixed array_search(mixed needle, array haystack [, boolean strict])
 Traversing array
 Using foreach loop
 foreach ($colors as $value)
{
echo "$value <br>";
}

5/18/2024
Determine Array size and uniqueness
38

 count()
 integer count(input_array)
 returns the total number of values found in the input_array.

 Sizeof() function can be also used.

 array_count_values()
 returns an array consisting of associative key/value pairs.
 Each key represents a value found in the input_array, and its
corresponding value denotes the frequency of that key’s
appearance (as a value) in the input_array.
 E.g. Array ( [Ohio] => 2 [Iowa] => 2 [Arizona] => 1 )

5/18/2024
Sorting Array
39

 sort()
 sorts the target_array, ordering elements from lowest to
highest value.
 rsort()
 is identical to sort(), except that it sorts array items in
reverse (descending) order.
 asort()
 is identical to sort(), sorting the target_array in
ascending order, except that the key/value
correspondence is maintained.

5/18/2024
Cont.…
40

 ksort()
 sorts the input array by its keys, returning TRUE on
success and FALSE otherwise.
 krsort()
 operates identically to ksort(), sorting by key, except
that it sorts in reverse (descending) order.

5/18/2024
Merging, Slicing, splicing and
41
Dissecting
 array_combine()
 array array_combine(array keys, array values)
 produces a new array consisting of keys residing in the
input parameter array keys, and corresponding values
found in the input parameter array values.
 both input arrays must be of equal size, and that
neither can be empty.
 E.g.$abbreviations = array("AL","AK","AZ","AR");
 $states = array("Alabama","Alaska","Arizona","Arkansas");
 $stateMap = array_combine($abbreviations,$states);

5/18/2024
Cont.…….
42

 array_merge()
 appends arrays together, returning a single, unified
array.
 If an input array contains a string key that already
exists in the resulting array, that key/value pair will
overwrite the previously existing entry.
 array_slice()
 array array_slice(array input_array, int offset [, int
length])
 returns the section of input_array, starting at the key
offset and ending at position offset + length.
5/18/2024
Cont.……
43

 array_splice()
 array array_splice(array input, int offset [, int length [,
array replacement]])
 removes all elements of an array, starting at offset and
ending at position offset + length, and will return those
removed elements in the form of an array.

5/18/2024
Cont.….
44

 array_intersect()
 The array_intersect() function returns a key-preserved
array consisting only of those values present in
input_array1 that are also present in each of the other
input arrays.
 array array_intersect(array input_array1, array
input_array2 [, array...])
 Note that array_intersect() considers two items to be
equal only if they also share the same datatype.

5/18/2024
Cont….
45

 array_diff()
 array array_diff(array input_array1, array
input_array2 [, array...])
 returns those values located in input_array1 that are
not located in any of the other input arrays.

5/18/2024
Function
46

 A block of code dedicated to achieve a single task.


 Advantages
 Reusability.
 Easy to maintain.

5/18/2024
Creating Function
47

 To call a function use its name, and if it has


parameters pass the required arguments.

5/18/2024
Passing Arguments
48

 Passing by value
 The original variable’s value will not be changed even
if the recipient variable value is changed.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

5/18/2024
Passing Arguments
49

 Passing by reference
 is done by appending an ampersand to the front of the
parameter(s).
 It changes the original variable's value.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>

5/18/2024
PHP Variable Length Argument
Function
50

 PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.
 The 3 dot concept is implemented for variable length argument since PHP 5.6.
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}

echo add(1, 2, 3, 4);


?>
Output:
10

5/18/2024
Default and Optional arguments
51

 Default values can be assigned to input arguments,


which will be automatically assigned to the
parameter if no other value is provided.
 E.g. function salestax($price,$tax=.0575)
 You can designate certain arguments as optional by
placing them at the end of the list and assigning
them a default value of nothing.
 function salestax($price,$tax="")

5/18/2024

Recursive Function
52

 Is a function which calls itself.


 It has condition to stop the iteration.
 E.g. a function that adds numbers b/n 1 and 10
<?php
function display($number) {
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}

display(1);
?>
5/18/2024
Functions in PHP…
53

Variable Scope
 A variable declared within a function remains local to that function.

 It will not be available outside the function or within other functions.

 PHP has fairly simple rules:


 Variables declared inside a function are in scope from the statement in which
they are declared to the closing brace at the end of the function. This is called
function scope. These variables are called local variables.
 Variables declared outside of functions are in scope of the statement in which
they are declared to the end of the file, but not inside functions. This is called
global scope. These variables are called global variables.
 Using require() and include() statements does not affect scope. If the statement is
used within a function, function scope applies. If it is not inside a function, global
scope applies.
 The keyword global can be used to manually specify that a variable defined or
used within a function will have global scope.
5/18/2024
Functions in PHP…
54

 Example: local variable


<?php
$num=50;
function test()
{
$testvariable = "this is a test variable";
echo “Num is ”, $num; //output: Num is
}
echo "test variable: $testvariable"; //output: test variable:
echo “Num is ”, $num; //output: Num is 50
?>

 The value of the variable $testvariable is not printed.


 This is because no such variable exists outside the test() function.
 Similarly, a variable declared outside a function will5/18/2024
not automatically be
available within it.
Functions in PHP…
55

 If you want a variable created within a function to be global, we can use


the keyword global as follows:
function fn()
{
global $var;
$var = “contents”;
echo “inside the function, \$var = “.$var.”<br>”;
}
fn();
echo “outside the function, \$var = “.$var.”<br>”;

 output:
inside the function, $var = contents
outside the function, $var = contents

5/18/2024
Functions in PHP…
56

 In PHP global variables must be declared global inside a function if they


are going to be used in that function.
<?php
$a = 1;
$b = 2;
function Sum() {
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>

 The above script will output "3".


 By declaring $a and $b global within the function, all references to either
variable will refer to the global version. 5/18/2024
Functions in PHP…
57

 A second way to access variables from the global scope is to use the
special PHP-defined $GLOBALS array.
 The previous example can be rewritten as:
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum();
echo $b;
?>
5/18/2024
Functions in PHP…
58

 Exercise
1. Write a function that accepts a number and returns
the squared and cubed value of the number.
2. Write a function that accepts a number as parameter
and then calculates the factorial of the number and
return it.
3. Write a function that accepts price of a commodity
and then calculates VAT tax(15%) and return it.
4. Write a function that calculates compound interest on
principal.

5/18/2024
Class
59

 It is a data type.
 Collection of objects.
 It is composed of fields and methods.
 E.g. class classname
{
// Field declarations defined here
// Method declarations defined here
}

5/18/2024
Objects
60

 Is an instance of a class.
 The practice of creating objects based on
predefined classes is often referred to as class
instantiation.
 Objects are created using the new keyword.
 E.g.
 $employee = new Staff();

5/18/2024
Invoking Fields and Method
61

 Fields are referred to using the -> operator and,


unlike variables, are not prefaced with a dollar
sign.
 Syntax:-
 $object->field
 When you refer to a field from within the class in
which it is defined, it is still prefaced with the ->
operator, although instead of correlating it to the
class name, you use the $this keyword or object
name.

5/18/2024
Cont.…..
62

 Field Scopes
 PHP supports five class field scopes: public, private,
protected, final, and static.
 Public
 Public fields can then be manipulated and accessed directly by a
corresponding object.
 Private
 Private fields are only accessible from within the class in which
they are defined.
 Protected
 Protected fields are also made available to inherited classes for
access and manipulation, a trait not shared by private fields.
 final

5/18/2024
Methods
63

 A method is quite similar to a function, except that it


is intended to define the behavior of a particular
class.
 E.g. public function scope function functionName()

{
/* Function body goes here */
}
$object->method_name();

5/18/2024
Constructors
64

 It is a block of code that automatically executes at


the time of object instantiation.
 PHP recognizes constructors by the name
__construct.
 Syntax:-
function __construct([argument1, argument2, ..., argumentN])
{
/* Class initialization code */
}

5/18/2024
Static Class Members
65

 Static members of a class are shared by multiple


objects and they belong to a class.
 Syntax:-
 Public static variable_name;
 Static function function_name(){}

 Autoloading Objects
 require_once("classes/Books.class.php");

5/18/2024
Form Handling
66

 We can create and use forms in PHP. To get form


data, we need to use PHP superglobals $_GET and
$_POST.
 The form request may be get or post. To retrieve
data from get request, we need to use $_GET, for
post request $_POST.

5/18/2024
PHP Get Form
67

 Get request is the default form request. The data


passed through get request is visible on the URL
browser so it is not secured. You can send limited
amount of data through get request.
 Let's see a simple example to receive data from get
request in PHP.
 File: form1.php

5/18/2024
68

 File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $
name variable
echo "Welcome, $name";
?>

5/18/2024
PHP Post Form
69

 Post request is widely used to submit form that have


large amount of data such as file upload, image
upload, login form, registration form etc.
 The data passed through post request is not visible
on the URL browser so it is secured. You can send
large amount of data through post request.
 Let's see a simple example to receive data from
post request in PHP.

5/18/2024
70

 File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td>
</tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>

5/18/2024
71

 File: login.php
 <?php
 $name=$_POST["name"];//receiving name field value in $name v
ariable
 $password=$_POST["password"];//receiving password field valu
e in $password variable
 echo "Welcome: $name, your password is: $password";
 ?>

5/18/2024
GET vs. POST
72

 Both GET and POST create an array (e.g. array( key =>
value, key2 => value2, key3 => value3, ...)). This array
holds key/value pairs, where keys are the names of the form
controls and values are the input data from the user.
 Both GET and POST are treated as $_GET and $_POST.
These are super globals, which means that they are always
accessible, regardless of scope - and you can access them
from any function, class or file without having to do
anything special.
 $_GET is an array of variables passed to the current script
via the URL parameters.
 $_POST is an array of variables passed to the current script
via the HTTP POST method.

5/18/2024
When to use GET?
73

 Information sent from a form with the GET method is visible


to everyone (all variable names and values are displayed
in the URL). GET also has limits on the amount of information
to send. The limitation is about 2000 characters. However,
because the variables are displayed in the URL, it is possible
to bookmark the page. This can be useful in some cases.
 GET may be used for sending non-sensitive data.
 Note: GET should NEVER be used for sending passwords or
other sensitive information!
 Generally we can use Get when there is
 Not sensitive data
 Not large amount of data ( about 2000 characters)
 Can bookmark

5/18/2024
When to use POST?
74
 Information sent from a form with the POST method is
invisible to others (all names/values are embedded within
the body of the HTTP request) and has no limits on the
amount of information to send.
 Moreover POST supports advanced functionality such as
support for multi-part binary input while uploading files to
server.
 However, because the variables are not displayed in the
URL, it is not possible to bookmark the page.
 Generally we can use post when there is
 Sensitive information
 Large amount of data
 It Can not bookmark

Developers prefer POST for sending form data.


5/18/2024
PHP Include File
75

 PHP allows you to include file so that a page


content can be reused many times. There are two
ways to include file in PHP.
 include
 require

 Advantage
 Code Reusability: By the help of include and require
construct, we can reuse HTML code or PHP script in many
PHP scripts.

5/18/2024
Forms - Validate
76

 Validate Form Data With PHP


 The first thing we will do is to pass all variables through PHP's
htmlspecialchars() function.
 When we use the htmlspecialchars() function; then if a user tries to submit
the following in a text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code,
like this: &lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;
 The code is now safe to be displayed on a page or inside an e-mail.
 We will also do two more things when the user submits the form:
 Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP
trim() function)
 Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
trim($data);
stripslashes($data);
htmlspecialchars($data);

5/18/2024
Forms - Validate
77

 PHP - Validate Name


 The code below shows a simple way to check if the
name field only contains letters and whitespace. If
the value of the name field is not valid, then store
an error message:
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}

5/18/2024
Forms - Validate
78

 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:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}

5/18/2024
Forms - Validate
79

 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:
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

5/18/2024
PHP include example
80

 PHP include is used to include file on the basis of given


path. You may use relative or absolute path ofFile:
menu.html
<a href="index.html">Home</a> |
<a href="php-tutorial.html">PHP</a> |
<a href="java-tutorial.html">Java</a> |
<a href="html-tutorial.html">HTML</a>
 File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>

5/18/2024
PHP require
81

 PHP require is similar to include. Let's see a simple


PHP require example.
 File: menu.html
<a href="index.html">Home</a> |
<a href="php-tutorial.html">PHP</a> |
<a href="java-tutorial.html">Java</a> |
<a href="html-tutorial.html">HTML</a>

 File: require1.php
<?php require("menu.html"); ?>
<h1>This is Main Page</h1>

5/18/2024
PHP include vs PHP require
82

 It is possible to insert the content of one PHP file into


another PHP file (before the server executes it), with the
include or require statement.
 The include and require statements are identical, except
upon failure:
 require will produce a fatal error (E_COMPILE_ERROR) and stop the
script
 include will only produce a warning (E_WARNING) and the script will
continue

 If file is missing or inclusion fails, include allows the script to


continue but require halts the script producing a fatal
E_COMPILE_ERROR level error.

5/18/2024
 Be the digger of

Live For What You Believe!!!!!!!


End of Chapter Two

Question
Comment

Thank you!

You might also like