IT3406-Teachers Note Section 1 2
IT3406-Teachers Note Section 1 2
& MySQL
IT3406 – Web Application Development II
Level II - Semester 3
• 1.2.2. Arrays and data processing with arrays [Ref 1: Pg. (206)]
[Ref 10 : Pg. (296-305)]
• 1.2.3. Handling HTML forms with GET and POST operations [Ref
1: Pg. (343)]
• 1.2.4. Form validation fields ( including URLs and email address)
and required fields [Ref 10: Pg. (574-585)]
• 1.2.5. Filtering inputs ( validate and sanitize external inputs) [Ref
1: Pg. (384-389)] [Ref 10: Pg. (432)]
• 1.2.6. Session control and cookies ( create and retrieve a cookie)
PHP [Ref 1: Pg.(419-435)][Ref 10: Pg. (437-446)]
• 1.2.7. File handling (Open, read, create, write operations with files,
upload files ) PHP [Ref 10: Pg. (366-368)]
• 1.2.8. Sending emails using PHP [Ref 11]
• 1.2.9. Object Orientation with PHP [ Ref 1. Pg. (395-418)]
• 1.3. Use web services with PHP [Ref 10: Pg. (541-553)]
• Write the PHP code in the left hand side text area.
• Click “Run” button to start processing (an animation will
start).
• See the output in the right hand side of the page.
Network/Interne
t
1
© 2020 e-Learning Centre, UCSC
0
Activity : Installing PHP with XAMPP in Windows
1
© 2020 e-Learning Centre, UCSC
1
Activity : Installing PHP with XAMPP in Windows
1
© 2020 e-Learning Centre, UCSC
2
Activity : Installing PHP with XAMPP in Windows
1
© 2020 e-Learning Centre, UCSC
3
Activity : Installing PHP with XAMPP in Windows
1
© 2020 e-Learning Centre, UCSC
4
Activity : Installing PHP with XAMPP in Windows
1
© 2020 e-Learning Centre, UCSC
5
Activity : Installing PHP with XAMPP in Windows
1
© 2020 e-Learning Centre, UCSC
6
Activity : Installing PHP with XAMPP in Windows
1
© 2020 e-Learning Centre, UCSC
7
Activity : Installing PHP with XAMPP in Windows
Problems?
• If you do not get the results as given above there are
few things to check!
• Is there another server running in default port used by
apache server (port:80) ?
• Restarting the computer if it is not already done from
the installer.
• Go to FAQ section for XAMPP:
https://www.apachefriends.org/faq_windows.html
• Other places to look for help:
• https://community.bitnami.com/t/xampp-installation-
problem/50826
• https://stackoverflow.com/
1
© 2020 e-Learning Centre, UCSC
8
Explain the basic features of PHP
Explain basic features of PHP
2
© 2020 e-Learning Centre, UCSC
0
Explain basic features of PHP
2
© 2020 e-Learning Centre, UCSC
1
Activity : Write a PHP script and test
• We already tried the phpinfo page in the XAMPP installation.
• Here we create a PHP page on our own and try to access it.
• Let us create a php script in xampp htdocs directory.
• Write the following code in your favorite text editor and save it
as hello.php
• We do not write any executable code here, we show
embedding a PHP segment inside HTML markup as follows :
2
© 2020 e-Learning Centre, UCSC
2
Activity : Write a PHP script and test
• The apache server connected to our PHP installation
contains specific directory that it looks for an executable
scripts.
• Here in XAMPP by default this directory is
<installation_path>/htocs.
• This path can be seen in the configuration file of XAMPP
properties.ini file with key:
apache_htdocs_directory=C:\xampp/htdocs.
• This document path is normally (non-XAMPP installations)
under the configured in key : DocumentRoot
"C:/xampp/htdocs” in the server’s
<server_root>/conf/httpd.conf file.
2
© 2020 e-Learning Centre, UCSC
3
Activity : Write a PHP script and test
2
© 2020 e-Learning Centre, UCSC
4
What is PHP?
2
© 2020 e-Learning Centre, UCSC
5
How does PHP work?
How PHP scripts are processed in web environment?
• Client sends a request to web server to access a PHP script
• The server checks if such a resource is available in the server
• If exists server send the script to the PHP interpreter together
with the parameters given by the client (if any)
• PHP interpreter executes the instructions in the script
• Access any other resources if required (accessing file system,
accessing database(s), accessing mail server(s) etc..)
• Interpreter sends the output of the script to the server
• Server sends it back to the client.
2
© 2020 e-Learning Centre, UCSC
6
Difference between an interpreter and compiler
2
© 2020 e-Learning Centre, UCSC
7
2
© 2020 e-Learning Centre, UCSC
8
Explain basic features of PHP
<?php
echo “Hello from PHP!”;
?>
• We can execute php scripts with or without the server
•Let’s execute the script at the command line by directly
invoking the PHP interpreter
php hello4php.php
2
© 2020 e-Learning Centre, UCSC
9
Explain basic features of PHP
<html>
<body>
<?php echo(“Some PHP code”); ?>
</body>
</html>
3
© 2020 e-Learning Centre, UCSC
0
Data types and Constants
Data types
3
© 2020 e-Learning Centre, UCSC
2
Data types
3
© 2020 e-Learning Centre, UCSC
3
Data types
3
© 2020 e-Learning Centre, UCSC
5
Integer Data : Activity
Represent the following integers with PHP echo command
and find the decimal representation by running the script. i.e:
<?php echo 1234; ?>
• 1234 // a positive integer in decimal form
• -123 // a negative integer in decimal form
• 0123 // integer 83 in octal form
• 0x2b1 // integer 689 in hexadecimal form
// integer 13 in binary form
• 0b01101
3
© 2020 e-Learning Centre, UCSC
6
Data types
3
© 2020 e-Learning Centre, UCSC
7
Decimal Floating Point
Representation
3
© 2020 e-Learning Centre, UCSC
8
Data types
3
© 2020 e-Learning Centre, UCSC
9
Data types
4
© 2020 e-Learning Centre, UCSC
0
Data types
Operator Operation
$x and $y True if both $x and $y are true
4
© 2020 e-Learning Centre, UCSC
1
Activity : Data types
<?php
echo -3,"\t",5 - 3,"\t",5.2*3.4,
"\t",10/2,"\t",
10/4,"\t",10%3,"\n";
?>
4
© 2020 e-Learning Centre, UCSC
2
Data types
4
© 2020 e-Learning Centre, UCSC
3
Data types
Example :
<?php
echo "This is a string literal","\n";
echo 'Another string literal';
?>
4
© 2020 e-Learning Centre, UCSC
4
Data types
4
© 2020 e-Learning Centre, UCSC
5
Activity : Data types
Example :
<?php
echo 'How the character sequence \n
works'; //not recognized
echo "A PHP string is represented by
\”String\” ";
echo ‘Bill spent 5$ for food’ ;//not
recognized as variable
?>
4
© 2020 e-Learning Centre, UCSC
6
Activity : Data types
<?php
echo 'Bill spent 5 $bills for food' ;
echo "Bill spent 5 $bills for food" ;
?>
4
© 2020 e-Learning Centre, UCSC
7
Data types
4
© 2020 e-Learning Centre, UCSC
8
Data types
5
© 2020 e-Learning Centre, UCSC
1
Data types
5
© 2020 e-Learning Centre, UCSC
2
Activity : Data types
5
© 2020 e-Learning Centre, UCSC
3
Activity : Data types
5
© 2020 e-Learning Centre, UCSC
4
5
© 2020 e-Learning Centre, UCSC
5
print and echo, are they similar?
5
© 2020 e-Learning Centre, UCSC
6
Constants
5
© 2020 e-Learning Centre, UCSC
7
Activity: Constants
5
© 2020 e-Learning Centre, UCSC
8
Variables and Operators
60
Variables
• A variable is a container of an object in a programming
environment.
• Variables can represent memory locations of your
computer.
• Since the data/value containing in a memory location can
change the variable’s value can change over the execution
of a program.
• What type of object a variable can represent in your
program depends on the data type of the given variable.
• i.e. : An integer type variable may represent a whole
number stored in the computer memory and so on…
6
© 2020 e-Learning Centre, UCSC
1
Variables
Rules for PHP variables:
•A variable starts with the $ sign, followed by the
name of the variable.
•A variable name must start with a letter or the
underscore _ character.
•A variable name cannot start with a number.
•A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ ).
•Variable names are case sensitive ($y and $Y are
two different variables).
6
© 2020 e-Learning Centre, UCSC
2
Variables
The variables in PHP are declared by appending the $
sign to the variable name, i.e.:
$company = “UCSC”;
$sum = 10.0;
1. local
2. global
3. static
6
© 2020 e-Learning Centre, UCSC
4
Local Scope
6
© 2020 e-Learning Centre, UCSC
5
Global Scope
6
© 2020 e-Learning Centre, UCSC
6
Global Scope
• However the global keyword can be used to access a global
variable from within a function.
• To do this, use the global keyword before the variables
(inside the function):
6
© 2020 e-Learning Centre, UCSC
7
Static Scope
• Normally, when a function is completed/executed, all of its
variables are deleted. However, sometimes we want a local
variable NOT to be deleted. (i.e.: we can use to count the
function calls.)
• To do this, use the static keyword when you first declare
the variable:
6
© 2020 e-Learning Centre, UCSC
8
Operators
6
© 2020 e-Learning Centre, UCSC
9
Arithmetic Operators
•Summary of basic mathematical operators in PHP
7
© 2020 e-Learning Centre, UCSC
0
Boolean (Logical) Operators
▪ The following operators can be applied
on both integers and floating point
numbers.
Operator Result
and, && TRUE when both operands are TRUE
or, || TRUE when either operand is TRUE
xor TRUE when either operand is TRUE, but not both
! negation
7
© 2020 e-Learning Centre, UCSC
1
Activity: Operators
•Find the output of the following code fragment.
<?php
$x = 3;
$y = 5;
$z = 4;
?>
7
© 2020 e-Learning Centre, UCSC
2
Activity: Operators
$x = 3;
$y = 5;
$z = 4;
?>
7
© 2020 e-Learning Centre, UCSC
3
Conditional Statements
Conditional Statements
7
© 2020 e-Learning Centre, UCSC
6
Conditional Statements
Syntax
if...elseif....else statement
<?php
$color=“Red”;
if (condition) {
//php code goes here if ($color ==“Red”) {
} elseif (condition) { echo “Please Stop“ ;
//php code goes here } elseif ($color ==“Yellow”)
{ echo “Get ready“ ;
} else {
} else {
//php code goes here echo “You can GO“ ;
} }
?>
7
© 2020 e-Learning Centre, UCSC
7
Conditional Statements
Syntax <?php
Switch
statement $favcolor="red";
select one of
many blocks switch ($favcolor) {
of code to be case "red":
executed. echo "Your favorite color is red!"; break;
case "blue":
echo "Your favorite color is blue!"; break;
case "green":
echo "Your favorite color is green!"; break;
default:
echo "Your favorite color is neither red, blue, or
green!";
}
?> 7
© 2020 e-Learning Centre, UCSC
8
Activity : Conditional statements
• Write a conditional statement to echo a string for a
number given in the variable $input as “red”,
“green”, “blue” and “yellow”.
• If the input is positive and even : red.
• If the input is positive and odd : blue.
• If the input is negative : green.
• If the input is zero yellow.
7
© 2020 e-Learning Centre, UCSC
9
Loops
Loops
▪ Loops are used when you need some block of code to be
executed over and over again.
▪ In PHP, we have the following looping constructs:
▪ while - loops through as long as the given condition is true
▪ do...while - loops through the code at least once, and then
repeats the loop as long as the given condition is true
▪ for - loops through a the code a given number of times
▪ foreach - loops through the code for each element in
a collection
8
© 2020 e-Learning Centre, UCSC
1
while Loop
<?php
while (condition is true) { $i=1;
//Code block; while($i<=5) {
} echo "Number: $i </br>";
$i++;
}
?>
Number: 1
Number : 2
Number : 3
Number : 4
Number : 5
8
© 2020 e-Learning Centre, UCSC
2
do-while loop
<?php
do {
//Php code $i=1;
} while (condition is true); do {
echo "Number: $i </br>";
$i++;
}while ($i<=5 && $i>1);
?>
Number: 1
Number : 2
Number : 3
Number : 4
Number : 5
8
© 2020 e-Learning Centre, UCSC
3
for loop
for (initialize counter; check; increment counter) {
//Do this;
}
8
© 2020 e-Learning Centre, UCSC
4
foreach loop
This works only on collections such as arrays
,lists <?php
foreach ($array as $value)
{ $person =
//Do this array("Nimal","Kamal","Sunil","Amal");
}
foreach ($person as $value) {
echo "$value \n";
}
Nimal ?>
Kamal
Sunil
Amal
8
© 2020 e-Learning Centre, UCSC
5
Activity : Loops
• Consider the following PHP statement:
$person = array("Dj","Kamal","de","Lanerole");
• Write a foreach loop to iterate through the $person array
and inside the loop there should be switch statement that
categorizes the array elements based on the length and
echos the “short\n” when the name is 0,1 or 2 characters
“medium” when 3,4 or 5 characters and “long” otherwise.
• (Note: You can combine conditions with grouped cases and
find the length of the name by strlen() function)
8
© 2020 e-Learning Centre, UCSC
6
Activity : Loops
Answer:
8
© 2020 e-Learning Centre, UCSC
7
Functions
Functions
▪ Functions make your code easy to read and make reusable.
▪ Large projects would be unmanageable without functions
because the problem of repetitive code that would bog
down the development process
▪ A function accepts values, processes them, and then performs
an action (printing to the browser, for example) and
optionally returns a new value.
▪ PHP has 2 types of functions
1. Language defined functions
2. User defined functions
8
© 2020 e-Learning Centre, UCSC
9
Built-in functions
▪ PHP has hundreds of language defined(built-in) functions .
For example strlen() returns the length of a string, in
characters .
<?php
echo strlen("Hello World!");
?>
Calling
<?php
the WriteWhoAmI();
Function ?>
<?php
function setMarks($minMark=50) {
echo "The Mark is : $minMark </br>";
}
setMarks(95);
setMarks(); // will use the default value of 50
setMarks(80);
?>
9
© 2020 e-Learning Centre, UCSC
4
Activity: Functions
Complete the factorial function skeleton given below
that computes the factorial for a positive integer
(factorial 5 = 5x4x3x2x1):
9
© 2020 e-Learning Centre, UCSC
5
8 5 7 1
0 1 2 3 4 5 6 7
4
3 2 6
Arrays
An array stores multiple values in one single variable
96
PHP Arrays
• One of the compound data types provided by PHP
is arrays.
• In general a PHP array is an ordered collection of
data items where each item in the collection is
associated with a key.
• In PHP, there are three types of arrays:
1. Indexed arrays - Arrays with a numeric index
2. Associative arrays - Arrays with named keys
3. Multidimensional arrays - Arrays containing one or
more arrays
9
© 2020 e-Learning Centre, UCSC
7
PHP Arrays
• PHP ‘indexed array’ with three String data elements.
9
© 2020 e-Learning Centre, UCSC
8
Construction of an array
• An associative array is
Syntax :
constructed by using the
language construct array(
array(array_elements) index_1 =>value_1,
index_2 => value_2,
• The array_elements
……………
comprises of a comma- index_n => value_n,
separated index,value
pairs, where each pair is
represented as index => The comma after the last array
value. element is optional and can be
omitted
9
© 2020 e-Learning Centre, UCSC
9
Construction of an array…
• The index of an example:
1
© 2020 e-Learning Centre, UCSC 0
Changing the value of an array
element.
example:
• The following syntax
can be used to $a = array(
change the value of 1=> "First Item",
"item2" => "Second
an array element.
Item",
5 => "Third item",
"Forth item"
$array_variable[index] );
= new_value;
$a[1] = “abc”;
$a[“item2”] = 25;
1
© 2020 e-Learning Centre, UCSC 0
Adding a new element to an array.
$array_variable[new_index] =
new_value;
Syntax :
array_push(array_variable, value1,value2,……)
Example :
$a = array("Nimal","Saman");
array_push($a,"Kamal","Waruna";
1
© 2020 e-Learning Centre, UCSC 0
Array of arrays
• Elements of an array can also be arrays.
example :
$a = array(
"males" => array("a" => "Nimal","b" =>
"Amara","c"
=>"Kamal"),
"females" => array("a" => "Kumari", "b" =>
"Nirmala", "c" =>
"Kamala"),
"fees" => array (2500,1500,500)
);
Syntax :
foreach (array_expression as $value)
statement Or
foreach (array_expression as $key =>
$value) statement
1
© 2020 e-Learning Centre, UCSC 0
Looping through array elements -
Example
<?php
$a = array(
1=> "First Item",
"item2" => "Second Item", 5 => "Third
item",
"Forth item"
);
1
© 2020 e-Learning Centre, UCSC 0
Multidimensional arrays
• Defining a two dimensional array: $cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
• Accessing the two dimensional array element by element:
1
© 2020 e-Learning Centre, UCSC 0
Handling Form Data
What is a form & how
they work in PHP?
112
Forms in HTML
• HTML forms is a powerful feature that enables
an application on a web server to interact with
users.
• HTML forms allow users to send data to
the web site.
• An HTML Form is typically made of a
collection of widgets such as text fields,
buttons, checkboxes, radio buttons or select
boxes.
• The “post” or “get” HTTP methods can be used
to send data to the server.
© 2020 e-Learning Centre, UCSC
1
1
Action and method attributes
• Two important attributes of the
“form” element are “action” and
“method”.
– action : specifies the URL of the web resource
designated to receive the data collected from
the form element.
– method : specifies which HTTP method (get or post)
should be used to send data to the receiving URL.
– If the receiving URL is a PHP program, then
depending on the method used in the HTML form
either the PHP superglobal $_GET or $_POST can be
used to access form data at the servers end. 1
© 2020 e-Learning Centre, UCSC 1
Example 1- Form with text inputs
<html>
<body>
<form action=“example.php" method="post">
Name: <input type="text"
name="name"><br>
<input type="submit"> The content of the example.php script is given below
</form>
<!DOCTYPE html>
</body>
<html>
</html> <body>
The name attribute specifies <div> Hello <?php echo
the key value of the $_POST $_POST["name"]?></div>
global array element from
</body>
which the value of this input
item can be retrieved
</html>
1
© 2020 e-Learning Centre, UCSC 1
Example 2- Form with check
<html>
boxes
<body>
<form action=“example.php"
method=“post"> Do you have an email?
<input type=“checkbox" name=“emailOption“ value
= “Yes”><br>
<input type="submit"></form>
</body>
</html>
When the user checked the checkbox,
the value “Yes” is send to the server
as the value of the attribute
“emailOption”.
1
© 2020 e-Learning Centre, UCSC 1
Example 2- check boxes ….
<html>
<body>
<div>
<?php
if($_POST["emailOption"]== "Yes"){
echo "Option is checked";
} else {
The data send to the
echo "Option is not-checked"; server can be
} accessed by using the
?> $_POST global array
element with the key
</div> value "emailOption"
</body>
</html>
1
© 2020 e-Learning Centre, UCSC 1
Example 3- Form with a check
box group
<html>
<body>
<form action=“example.php"
method=“post"> Which fruits do you like?
<input type=“checkbox" name=“fruits[]“ value = “Apples”>Apples<br>
<input type=“checkbox" name=“fruits[]“ value =
“Oranges”>Oranges<br>
<input type=“checkbox" name=“fruits[]“ value = “Grapes”>Grapes<br>
<input type="submit"> Note that the checkboxes have the same
name “fruits” and each name ends in [ ].
</form>
• The same name indicates that these checkboxes
</body> are all related and forms a group.
</html> • [ ] indicates that the selected values will be
provided to PHP script as an array.This means
That the $_POST[„fruitsr'] is an array not a
single string.
1
© 2020 e-Learning Centre, UCSC 1
Example 3- Form with a check box
group <html>
<body>
<div><?php
$fruits = $_POST["fruits"];
if(!empty($fruits)){
echo "You like ";
for($i=0; $i <
count($fruits);$i++){ echo
"<br>". $fruits[$i];
}
} else {
echo "You do not like any fruits";
}
?>
</div>
</body>
</html> 1
© 2020 e-Learning Centre, UCSC 1
Example 4- Form with a Radio
<html>
button
<body>
<form action="example.php"
method="post"> Please specify your sex
:<br>
<input type="radio" name="sex" value =
"male">male<br>
<input type="radio" name="sex" value
= "female">female<br>
<input type="submit">
Note that all radio buttons should
</form> have the same value for the attribute
“name”.
</body>
</html>
1
© 2020 e-Learning Centre, UCSC 2
Example 4- Form with a
<html>
Radio button ….
<body>
<div>
<?php
echo "you are a ".
$_POST["sex"];
?>
</div>
</body>
</html>
1
© 2020 e-Learning Centre, UCSC 2
Cookies
122
Cookies
• A cookie is a file with small amount of data that a
website embeds on the user’s computer through
a web browser. This cookie is send back to the
website by a browser every time when the user is
accessing the same website by using the same
browser.
• The browsers can either enable or disable cookies.
• In PHP data stored in cookies can be accessed
by using the global array $_COOKIE
1
© 2020 e-Learning Centre, UCSC 2
Modifying the value of a
cookie
• To modify the <?php
setcookie("name",“Kamal",tim
value of a cookie
e()+3600);
call the same ?>
function
setcookie() with
the new value.
1
© 2020 e-Learning Centre, UCSC 2
Deleting a cookie.
• To delete a <?php
setcookie("name",“Kamal",tim
cookie execute e()-3600);
the same ?>
setcookie()
function with an
expiration date
in the past.
1
© 2020 e-Learning Centre, UCSC 2
File Handling
130
Typical operations on files
• Opening a file
• Adding data
• Accessing data
• Closing the file
1
© 2020 e-Learning Centre, UCSC 3
Opening a File
File opening modes
Syntax: w – write
fopen ( $filename , $mode r – reading
[,$use_include_path = false a – appending
[,
$context ]] ) fopen returns a file
fopen() binds the resource named pointer resource on
as success or FALSE
on failure
$filename, to a stream.
• If a file named “mydata.txt” exists then the content
of the file is deleted.
• If there is no file with the name “mydata.txt” then a new
file with the name “mydata.txt” is created.
1
© 2020 e-Learning Centre, UCSC 3
Writing data to a file
<?php
$f =
fwrite returns the
fopen("data.txt","w");
number of bytes
fwrite($f,"My name is
written to the file or
saman\n");
FALSE on
fwrite($f,"My age is failure.
90"); fclose($f);
?>
Syntax of fwrite :
fwrite ( $handle , $string [, $length ] )
fwrite() writes the content of $string to the file stream pointed to by
$handle. If the optional length argument is given, writing will stop after
$length number of bytes is written or the end of string is
reached,
whichever comes first. 1
© 2020 e-Learning Centre, UCSC 3
Appending data to a file
<?php
$f = fopen("data.txt",“a");
fwrite($f,"My name is
Sunil\n"); fclose($f);
?>
1
© 2020 e-Learning Centre, UCSC 3
Reading data from a file – fgets()
Syntax: <?php
file ( $filename) $lines= file(“data.txt");
Semantics: foreach($lines as
$line_no => $line){
• Reads the entire file echo
$filename into an array. $line_no,$line,"<br>";
• The command returns }
?>
– The file in an array. Each
element of the array
corresponds to a line in the
file or
– FALSE if an error occurs.
1
© 2020 e-Learning Centre, UCSC 3
Reading data from a file – file()
Syntax:
fgets ( $handle [,$length ] )
Semantics:
• Reads a line from the file pointed to by the file pointer $handle.
• The command returns
– A line of symbols (including the end of line marker) from the file as
a string when the $length parameter is not specified or
– A string of up to length - 1 bytes from the file when
$length parameter is specified or
– The Boolean value FALSE when there is no more data to read in
the file or
– The Boolean value FALSE if an error occurred while reading the file.
1
© 2020 e-Learning Centre, UCSC 3
Reading data from a file – fscanf()
Syntax:
fscanf( $handle, $format)
<?php
$f = fopen("data.txt","r");
Semantics: while ($line =
• Reads a line of the file fscanf($f,"%s\t%d\n")){
pointed to by the file echo $line[0],"-
pointer $handle according ",$line[1],"<br>";
to the format specified by
}
the string $format.
?>
• The command returns
– the values parsed as
an array.
1
© 2020 e-Learning Centre, UCSC 3
Reading data from a file -
Example
<?php
$f =
fopen("data.txt","r")
;
while (! feof($f)){
$line = fgets($f);
echo $line, "<br>";
}
fclose($f);
?>
1
© 2020 e-Learning Centre, UCSC 3
Existence of a file/directory
Command : file_exists() <?php
if(!file_exists(
Syntax :
"data.txt")){
file_exists($filename) echo "File does not
Semantics : exists"; exit;
}
Checks the existence of a echo "File Exists";
file or directory. ?>
It returns the Boolean
value TRUE when the
file/Directory exists,
otherwise it returns
FALSE.
1
© 2020 e-Learning Centre, UCSC 3
Sending emails using PHP
PHP Mail function
The mail() function allows you to send emails directly
from a script.
• The mail functions are part of the PHP core
functions. For the mail functions to be available,
PHP requires an installed and working email
system.
• The program to be used is defined by the
configuration settings in the php.ini file.
1
© 2020 e-Learning Centre, UCSC 4
1
© 2020 e-Learning Centre, UCSC 4
PHP Mail function
The mail() function needs configuration settings to
work properly in php.ini file, some of them:
Name Default Description Changeable
Windows only: The DNS name
SMTP "localhost" or IP address of the SMTP PHP_INI_ALL
server
1
© 2020 e-Learning Centre, UCSC 4
Object Orientation with PHP
Object-Oriented Programming
• Object Oriented Programming (OOP) refers to the
creation of reusable software components(classes)
that integrate properties(data) and behaviors
(functions) of real-world entities together.
• In OOP an object can represents any entity. (a
student, a desk, a button, a file, a text input area, a
loan, a web page or a shopping cart)
• An object-oriented program comprises of a
collection of such objects that interact with each
other to solve a particular problem/s.
1
© 2020 e-Learning Centre, UCSC 4
Object-Oriented Programming
• Objects are self-contained
– data and operations that pertain to the
object are assembled into a single entity.
• In OOP each Object has:
– An identity
– State
– Behavior
1
© 2020 e-Learning Centre, UCSC 4
Building Objects According to a Template/Blue print/Plan
#C62A6A
1
© 2020 e-Learning Centre, UCSC 4
Class and Object
• A “Class” refers to a blueprint. It defines the
attributes(variables) and
behaviors(functions) the objects of that class
should support.
• An “Object” is an instance of a class. Each
object should corresponding to a class(es)
which defines its attributes and behavior.
1
© 2020 e-Learning Centre, UCSC 4
The Class
• The basic unit of code in object-oriented PHP is the class.
A class provides a mechanism to encapsulate related
functionality and data into a single entity.
• In PHP a class can be defined by using the keyword
‘class’ as below.
• The class name can be any valid label and it cannot be
a PHP reserved word.
Class Name
class Circle
{
// Class properties and Properties
methods
} Methods
1
© 2020 e-Learning Centre, UCSC 5
Properties
• In PHP5, class properties are used as placeholders,
to store data associated with the objects of that class.
The visibility of a property can be defined by adding
one of the following prefixes to the declaration of the
property.
– public : the value of the property can be accessed
from everywhere. If no visibility is specified for a
method, it defaults to public visibility.
– protected : the value of the property can be accessed
only by the class and the derived classes(child classes).
– private : the value of the property can be accessed only by
the class that defines the member.
1
© 2020 e-Learning Centre, UCSC 5
A Class with Public and Private
Properties - Example
class Person{
public $name;
public $dob;
private $bank_account_no;
1
© 2020 e-Learning Centre, UCSC 5
Creating objects(Instances) of a
class
• In order to access the properties and use the methods of a class,
you first need to instantiate, or create an instance(object). This
can be done by using the keyword ‘new’ as below:
$c = new Person();
Classes should be defined before instantiation.
$c variable holds a reference to an instance (object) of the
class ‘Person’.
$c->name = “Sunil”;
1
© 2020 e-Learning Centre, UCSC 5
Object assignments
• When assigned an already created instance of a
class to a new variable, the new variable also
points to the same instance. Example :
$p1 = new Person();
$p1->name = "Sunil";
$p2 = $p1; // $p1 and $p2 points to the same object
$p2->name = "Kamal";
echo $p1->name; // This will print the text “Kamal”
as $p1 and $p2 points
to the same object
1
© 2020 e-Learning Centre, UCSC 5
Class Methods
• Class properties are used to hold data inside
objects. Functions can be created inside a class to
manage its property values. Such functions defined
inside classes are called its methods.
1
© 2020 e-Learning Centre, UCSC 5
Class Methods
class Person{
public $name;
public $sex = "m"; // default
value
public $dob; $this is a The
private $bank_account_no = ; pseudo-
variable. It is
Public function set_name($name){ used to refer
to the calling
$this->name = $name; object to
} which the
method
Public function print_name(){ belongs.
echo $this->name;
}
1
} © 2020 e-Learning Centre, UCSC 5
Constructors and Destructors
• In some situations when dealing with classes,
you might want to have a way to automatically
initialize object variables and/or to perform
certain pre-defined actions when the object is
created. For such situations, a constructor can be
used.
• A constructor is nothing more than a specially
named method that is automatically called when
an object is instantiated. In PHP5, to implement
a constructor, all you need to do is implement a
method named“__construct”.
1
© 2020 e-Learning Centre, UCSC 5
Constructors and Destructors
• PHP5 now includes a special method
(destructor) that is called when an object
is destroyed.
• An object destructor is called when all
references to an object are removed, or it
is manually destroyed in your code.
• To create a destructor, add a method to
your class, and call it “__destruct”.
1
© 2020 e-Learning Centre, UCSC 5
Class Object
{
function construct() {}
function destruct() {}
}
$obj=
newObject();
unset($obj);
159
<?php
class Person{
Example: _construct
public $name = null;
public $sex = "m";
public $dob;
private $bank_account_no;
function _construct($name,$sex,$dob,$acc){
$this->name = $name; $this->sex = $sex;
$this->dob = new DateTime($dob);
//$dob should be give as "2015-01-15"
$this->bank_account_no = $acc;
}
public function print_age($toData){
//$toDate should be give as "2015-01-15"
$interval = $this->dob->diff(new DateTime($toDate));
echo "Years - ". $interval->y . " Months - ".$interval->m ." Days
-
".$interval->d ;
}
}
1
© 2020 e-Learning Centre, UCSC 6
Example: self
<?php
class Person{
public $name = null;
public $sex = "m";
private static $ObjectCount =
0; function _construct($name,$sex){
$this->name = $name;
$this->sex = $sex;
self::$ObjectCount++;
}
public function print_object_count(){
echo "Number of objects instantiated -
". self::$ObjectCount;
}
}
1
© 2020 e-Learning Centre, UCSC 6
<?php
class Person{
const office = "UCSC";
public $name = null;
public $sex = "m";
function __construct($name,$sex){
$this->name = $name;
$this->sex = $sex;
Example:
} const
public function print_office(){
echo "Office name -".
self::office;
}
}
Person::print_office();
?>
1
© 2020 e-Learning Centre, UCSC 6
Inheritance
• Allows you to define a base set of properties and methods that belong to a
base class and to extend that class by
– adding additional properties and methods and/or
– changing the behavior of existing methods.
• The subclass inherits all of the public and protected properties and
methods from the parent class. Unless a subclass overrides a method, the
subclass retains its original functionality defined in the parent class.
• Inheritance facilitate the implementation of additional functionality in
similar objects without the need of re- implementing all of the shared
functionality.
• When defining a subclass the parent class must be defined before defining the
child class.
1
© 2020 e-Learning Centre, UCSC 6
1
© 2020 e-Learning Centre, UCSC 6
The extends key word
<?php
The keyword
class Shape extends is used
{ to build a
public $center = subclass
array(x=>0, y=>0);
}
class Circle extends Shape Parent
{ Class
public $radius;
}
$c = new Circle();
print_r($c->center);
?> IT3505 Web Application
© 2020 e-Learning Centre, UCSC
1
6
The final Keyword
• There are cases where, you want to restrict a
subclass from redefining a member that exists
in a parent class.
• You can prevent properties and methods
from being redefined(overriding) in a subclass
by using the final keyword.
1
© 2020 e-Learning Centre, UCSC 6
Using parent:: References
• In some situations you may want to refer to a
property or a method of the parent class, in a
subclass.
• To achieve this, you can use the parent
keyword in conjunction with the :: (double
colon) similar to static members.
1
© 2020 e-Learning Centre, UCSC 7
<?php
class Shape {
var $x;
function getName()
{
$this->x = “I’m a shape";
return;
}
}
class Circle extends Shape {
// we have var $x; from the parent already here.
function getParentName()
{
parent:: getName();
echo $this->x;
}
}
$b = new Circle();
$b-> getParentName(); // prints: " I’m a shape "
?>
1
© 2020 e-Learning Centre, UCSC 7
Abstract Classes
• When a class is defined as abstract, other
classes can extend it, but it cannot be
instantiated. This feature enables you to define
classes as templates.
• A class that contains at least one abstract
method is treated as an abstract class.
• Abstract methods only defines the signature
of the method, but not its implementation.
• When inheriting from an abstract class, all
methods declared as abstract in the parent
class must be defined by the child.
1
© 2020 e-Learning Centre, UCSC 7
<?php
abstract class Shape{
public $origin = array(x=>0, y=>0);
}
$c = new Circle();
echo $c->origin;
$s = new Shape(); echo $s-
>origin;
?>
1
© 2020 e-Learning Centre, UCSC 7
Interfaces
• Another new object-oriented feature in PHP5 is the
ability to create and use interfaces. Interfaces, in a
nutshell, are a way to specify what methods a class
must explicitly implement. This is useful when
dealing with many interconnected objects that rely
on the specific methods of one another.
• In PHP5, an interface is defined using the
interface keyword, and implemented using the
implements keyword.
• All methods declared in an interface must be public.
• Interfaces can be extended like classes
using the extends operator.
1
© 2020 e-Learning Centre, UCSC 7
Interfaces
interface TwoDimensionalOperations
{
public calculateArea() ;
}
class Circle implements
TwoDimensionalOperations
{
public calculateArea() ;
{
// Implementation of calculateArea,
specific to this Circle class
}
} 1
© 2020 e-Learning Centre, UCSC 7
Abstract Classes Vs Interfaces
• A child class can extend only one abstract
class, whereas a class can implement
multiple interfaces.
• An interface does not provide any
functionality (method implementations)
whereas an abstract class may provide
some functionality.
1
© 2020 e-Learning Centre, UCSC 7
Magic Methods
• Magic methods is a set of methods designed to be
executed automatically in response to particular
PHP events.
• All names of magic methods starting with
two underscores.
• PHP reserves all function names starting with “__” as
magical, thus it is recommended not to start any user
defined function with “__”.
i.e:
• __call
• __get and __set
• __toString
1
© 2020 e-Learning Centre, UCSC 7
__call()
• Allows you to provide actions or return values
when undefined methods are called on an object.
• Can be used to simulate method overloading,
or even to provide smooth error handling
when an undefined method is called on an
object.
public function __call($m, $a){
echo “The method ” . $m . “ was called.<BR> The
arguments were as follows:<BR>;
print_r($a);
}
1
© 2020 e-Learning Centre, UCSC 7
__get and __set
• __get allows properties which actually not
accessible in a class to be read.
• __set allows properties which actually not
accessible in a class to be written.
• __get takes one argument - the name of
the property.
• __set takes two arguments - the name of the
property and the new value.
1
© 2020 e-Learning Centre, UCSC 7
__toString
• __toString returns a custom string value
that is automatically used when the object
is converted to a string.
• Only called when used directly with echo or
print. If not implemented in a class the
object id will be returned by default.
1
© 2020 e-Learning Centre, UCSC 8
Activity: Classes
• Complete the PHP class given below according to the
comments.
1
© 2020 e-Learning Centre, UCSC 8
Activity: Classes
Answer:
1
© 2020 e-Learning Centre, UCSC 8
Developing a web application
with PHP
Technology Stack
Apache
Operating System
1
© 2020 e-Learning Centre, UCSC 8
How does the Apache/PHP/MySQL web application
work?
1
© 2020 e-Learning Centre, UCSC 8
Introduction to MySQL
• A free and open source relational database
management system (RDBMS)
• MySQL is used by many database-driven web
applications, including Drupal, Joomla, phpBB,
and WordPress together with PHP.
• MySQL is also used by many popular websites,
including Facebook, Flickr, MediaWiki, Twitter
and YouTube.
1
© 2020 e-Learning Centre, UCSC 8
Installation of MySQL
• We have more than one approach to install MySQL:
1. Download and install the MySQL server.
2. Use XAMPP bundled MySQL installation.
1
© 2020 e-Learning Centre, UCSC 8
Installation of MySQL
• To access the database click the Admin button.
1
© 2020 e-Learning Centre, UCSC 8
Creating a Database
• There are 2 main ways of creating a database
:
– With the command line
– By using a tool such as MySQL workbench
, phpMyAdmin
• Since you are using XAMPP
package, we will use the
phpMyAdmin to make tables.
1
© 2020 e-Learning Centre, UCSC 8
Creating a database by using
phpMyAdmin tool
1) Click on databases and give a suitable name . Click ‘ C2) Click ‘Create’
reate
’
1
© 2020 e-Learning Centre, UCSC 9
Creating Databases-(with SQL
command)
1
© 2020 e-Learning Centre, UCSC 9
Creating Table (GUI)
• You can create tables in a selected DB by
executing the relavent command or by using the
GUI
1
© 2020 e-Learning Centre, UCSC 9
Creating Tables (SQL
commands)
CREATE TABLE Persons ( PID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName CHAR(15),
LastName CHAR(15), Age INT )
1
© 2020 e-Learning Centre, UCSC 9
Managing data stored in
MySQL DBs Through
PHP
Basic Steps in Processing data stored
in MySQL through PHP programs
1. Connect to a host server with MySQL
installed.
2. Select a database
3. Create a SQL statement
4. Execute the SQL statement.
– Many SQL statements return the result of a SQL
statement as a record set
5. Extract data from record set using
PHP commands
6. Use the data as required
7. Close the connection 1
© 2020 e-Learning Centre, UCSC 9
Open a Connection to MySQL
• Opening a connection to a MySQL DB
<?php Usually "localhost"
$servername = "localhost";
$username = "username"; By default – ‘root’
$password = "password";
$dbname = “myDB"; By default – ‘ ’
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Database connection failed: " . $conn-
•
>connect_error);
}
echo "Success. Connected to database";
O
?>
1
© 2020 e-Learning Centre, UCSC 9
Open a Connection to MySQL
• Create a new user from the console to connect to the
database myDB
1
© 2020 e-Learning Centre, UCSC 9
Close the Connection
• It’s always a best practice to close a
connection once you are done with
working with the database.
• Can close the connection using this syntax.
// if the connection object is $conn
$conn->close();
1
© 2020 e-Learning Centre, UCSC 9
mysqli_query()
• This is one of the most important and
most used function in php when dealing
with MySQL.
• mysqli_query() function is used to command
PHP to execute a SQL statement.
• It sends a query or command to a
MySQL DBMS through the connection
object.
2
© 2020 e-Learning Centre, UCSC 0
Inserting Data Into a Database
Table
• You can use INSERT INTO statement to add
new records to a database table.
• There are 2 different ways of writing insert queries
– INSERT INTO table_name VALUES (value1, value2,
value3,...)
– INSERT INTO table_name (column1, column2,
column3,...) VALUES (value1, value2, value3,...)
• The first form can be used if data is inserted to all columns of
the new record.
• The second form can be used if data is inserted only to
a selected set of columns in the new record.
2
© 2020 e-Learning Centre, UCSC 0
Executing a SQL query through PHP
• The following PHP code segment inserts two record
to the table ‘Persons’
<?php Structure of the table
$con=mysqli_connect("localhost", "root", " ", Persons{
"myDB"); PID INT NOT NULL
if ($con->connect_error) AUTO_INCREMENT
die("Database connection failed: " . PRIMARY KEY,
$conn->connect_error); FirstName CHAR(15),
LastName CHAR(15),
Age INT )
mysqli_query($con,"INSERT INTO Persons (FirstName,
LastName, Age)VALUES
('Nimal', 'Perera',35)");
mysqli_close($con);
?>
2
© 2020 e-Learning Centre, UCSC 0
Inserting data to a MySQL DB
through a HTML form.
• This HTML page requests the web server to execute a PHP
script named “insert.php” at the server side.
<html>
<body>
<form action=“insert.php" method="post">
Firstname: <input type="text“
name="firstname"><br>
Lastname: <input type="text"
name="lastname"><br>
Age: <input type="text"
name="age"><br>
<input type="submit">
</form>
</body>
</html>
2
© 2020 e-Learning Centre, UCSC 0
Insert data into a database table
Content of the PHP script insert.php
<?php
$con=mysqli_connect("localhost","root","", “myDB");
if ($con->connect_error) die("Database connection failed:
“.$conn->connect_error);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$sql = "INSERT INTO persons (FirstName, LastName, Age)"
. "VALUES ( '$firstname', '$lastname', $age )";
if(mysqli_query($con,$sql)){
echo "Data inserted to the Table successfully";
}else {
echo "Error in inserting data". $con->error;
}
mysqli_close($con);
?>
2
© 2020 e-Learning Centre, UCSC 0
Selecting and Displaying Data
<?php
$con=mysqli_connect("localhost","root","",“myDB");
if ($con->connect_error) die("Database connection failed: " .
$conn->connect_error);
$sql = "select * from persons";
$result = mysqli_query($con,$sql);
if(!$result){
die("Error in executing the SQL" . $con->error);
}
while ($row = mysqli_fetch_array($result)){
echo $row['FirstName'] . " " . $row['LastName']. "<br>";
}
mysqli_close($con);
?>
selects all data stored in the “persons“ table and display only the content of the
‘FirstName’ and ‘LastName’ columns.
2
© 2020 e-Learning Centre, UCSC 0
Select Data satisfying a where
clause
• We can use the Where clause to filter data.
<?php records
$con=mysqli_connect("localhost","root","123456","bit
Earlier example
");
selected all the
if ($con->connect_error) die("Database connection
Records from
failed: " .
the table , but
$conn->connect_error);
here we are
$sql = "select * from persons where
using a where
FirstName='Nimal'";
clause to filter
$result = mysqli_query($con,$sql);
data so that it
if(!$result){
will only return
die("Error in executing the SQL" . $con->error);
records where
}
the First name
while ($row = mysqli_fetch_array($result)){
field is ‘Nimal’
echo $row['FirstName'] . " " . $row['LastName'].
"<br>";
}
mysqli_close($con);
?>
2
© 2020 e-Learning Centre, UCSC 0
MySQL Update
• Whenever you need to update a record
which exist in a table, you can use update
query.
UPDATE table_name Here the ‘Where’
SET column1=value, clause decide
column2=value2,... which records to
WHERE some_column=some_value be updated. If you
remove the WHERE
clause, all records
will be updated
2
© 2020 e-Learning Centre, UCSC 0
Changing Data in the DB
<?php
$con=mysqli_connect("localhost","root","",“myDB"
);
if ($con->connect_error) die("Database
This will search
connection failed: " .
for records
$conn->connect_error); which have
if(mysqli_query($con,"UPDATE Persons SET Age= 50 the Firstname
WHERE FirstName='Nimal'")){ as ‘Nimal’ and
echo "Record updated successful"; change the
} else { Age attribute
echo "Error in executing the SQL" . $con- of those
>error; records to ‘50’
}
mysqli_close($con);
?>
2
© 2020 e-Learning Centre, UCSC 0
Delete Data In a Database Table
• The delete query is used when you need to remove a
record from a table.
DELETE FROM table_name
WHERE some_column = some_value
<?php
$con=mysqli_connect("localhost","root","123456","bit"); if
($con->connect_error) die("Database connection failed: " .
$conn->connect_error);
if(mysqli_query($con, "DELETE from Persons WHERE
FirstName='Nimal'")){
echo "Record delete successful";
} else {
echo "Error in executing the SQL" . $con->error;
}
mysqli_close($con);
?>
2
IT3505 Web Application
© 2020 e-Learning Centre, UCSC Development 0
Frameworks & MVC
What is a framework ?
• A software framework is a re-usable design that can be
used to build a software system (or subsystem).
2
© 2020 e-Learning Centre, UCSC 1
Library vs. Framework
• A library performs specific, well-defined
operations whereas a framework is a skeleton
(abstract design) where the application defines
what exactly to be done by filling out the
skeleton.
• The main objective of a library is the code reuse.
• Typically, in a framework there is a defined control
flow with predefined spots that you should fill out
with our code. Your inserted code will be called by
the framework appropriately.
2
© 2020 e-Learning Centre, UCSC 1
Library vs. Framework
2
© 2020 e-Learning Centre, UCSC 1
Why Frameworks ?
• Raw PHP, works very well with small applications.
HTML files can be easily extended with dynamic
content from the database, form processing, etc.
• But, when applications grow, lots of code repetition
occurs across multiple pages.
• Many common tasks will be there for any given web
application that may need to redevelop when
programming from basic features.
• Its hard for a new developer to work on a code
someone else have written.
– It takes a long time to get familiar with the code.
2
© 2020 e-Learning Centre, UCSC 1
Model-View-Controller design
pattern
• Most common and popular Web application development
frameworks are based on the Model-View-Controller(MVC) design
pattern.
• A design pattern is a software design best practice derived from
experience.
• When the framework provides the building blocks of the proved
design pattern the developers can focus on the specific requirements
of the project under development.
• Recall in OOP a class is a blue print to generate multiple objects.
• In parallel a design pattern is a design guideline for a given program
design problem (i.e.: what is the suitable high-level design for a web
application?)
2
© 2020 e-Learning Centre, UCSC 1
Model-View-Controller design
pattern
• When Model-View-Controller pattern is implemented the
application is structured to logically separable functions
• For MVC such parts include data-model, presentation
aspect and the control flow.
• Typically, application frameworks provide basic building
blocks needed by most applications such as
– Database connections
– Business logic
– Form handling
2
© 2020 e-Learning Centre, UCSC 1
Features of a good framework
• Supports a design pattern.
• Provide libraries, plugins to make application development
easier and faster.
• Supports layer of abstraction for database
interactions
– Ability to work with a database without writing
queries by SQL language
• A strong community
– If something goes wrong, a place to get support.
2
© 2020 e-Learning Centre, UCSC 1
PHP Frameworks
There are many PHP framework. A number
of them are listed below
• CakePHP
• Symfony
• CodeIgniter
• Zend Framework
• Yii Framework
2
© 2020 e-Learning Centre, UCSC 1
PHP application testing and
tools
Web Application Testing
• In all areas of software development, including web
applications, testing is a crucial step.
• You must ensure the application works correctly
before handing it over to your customer.
• That process involves testing. There are generally four levels
of testing that you
can perform with dynamic web applications. From lowest to
highest levels.
2
© 2020 e-Learning Centre, UCSC 2
Web Application Testing
• Unit testing: Perform tests on individual sections of code to
ensure that there are no syntax or logic errors. In a web
application you can test individual functions/button events
and ensure there are no errors or warnings produced for
acceptable input.
• Integration testing: Perform tests on passing data between
different sections of code to ensure that there is no data
mismatch. Proper integration testing requires an overall
picture of system components(different pages) and the data
flow between them. Therefore a picture of the flow should
be kept when performing the testing.
Validation Sanitizing
Web Application Security
• Security is a very important area of Web application
development. The security aspect comparatively more
important than the non-web applications. There are reasons
for that:
• Web applications are exposed to internet, therefore anyone
with a computer and internet connection can reach the
application.
• Web applications use a web client that renders the
application content for the user in contrast to the direct
interface with a desktop application therefore we do not
have control over the client.
• Web content reaches the user through a public network in
contrast to the locally installed or restricted application.
2
© 2020 e-Learning Centre, UCSC 2
Web Application Security
Results of application security breaches:
• Sensitive data of both company and customers is
exposed
• Loss of trust by the customers
• Direct financial loss due to fraudulent transactions
etc.
• High cost of recovering the data, software and even
hardware
• Interruption of business
2
© 2020 e-Learning Centre, UCSC 2
Exploring PHP Vulnerabilities
• Cross-site scripting
• Data spoofing
• Invalid data
• Unauthorized file access
2
© 2020 e-Learning Centre, UCSC 3
Exploring PHP Vulnerabilities
• Cross-site scripting : Cross-site scripting (known as
XSS) is quite possibly the most dangerous type of
attack made on dynamic web applications. The
main idea of an XSS attack is to embed malicious
JavaScript code in data that the attacker submits to
the web application as part of the normal data
input process. When the web application tries to
display the data in a client browser, the JavaScript
is pushed to the client browser that’s viewing the
website and runs.
2
© 2020 e-Learning Centre, UCSC 3
Exploring PHP Vulnerabilities
Cross-site scripting attacks can be in two types:
• Persistent attack: The attacker places the rogue script as
data that the browser displays when the web page loads.
User only has to access the page to be exposed to the
malicious code. Attacker can keep a comment for a blog
post that runs as victim sees the comment.
• Reflected attack: The attacker places the rogue script as a
link in the submitted data. Victims must actively click the
link to launch the XSS attack. The attacker might send a link
through email which need to be clicked by the victim.
2
© 2020 e-Learning Centre, UCSC 3
Exploring PHP Vulnerabilities
Data spoofing : Data spoofing means externally inserting
fraudulent data into a PHP program code. PHP has a setting
called register_globals in the php.ini configuration file for the
PHP server.
• When this setting is enabled, PHP automatically converts
any data passed via the GET or POST methods into a PHP
variable.
• Attacker can use this feature to create a global variable
inside your PHP program by just sending an input parameter
with the required name.
• If such a variable is used by the program to take a decision
attacker can override the value of that variable making the
PHP code vulnerable.
2
© 2020 e-Learning Centre, UCSC 3
Exploring PHP Vulnerabilities
Invalid data : Invalid data inputs to a web application can be
due to two reasons.
• Human error of the user: Often invalid data is just the result
of a site visitor not paying close enough attention to the
form fields and entering the wrong data into the wrong
field, such as typing a zip code into a city name data field.
• Intentional input by an attacker: This can vary from as
entering an invalid email address into a contact form on
purpose to remain anonymous to inserting a data that may
reveal a system vulnerability/malfunction i.e. SQL injection.
• The application developer has to anticipate invalid data and
try to prevent it before it becomes a problem in the
application.
2
© 2020 e-Learning Centre, UCSC 3
Exploring PHP Vulnerabilities
Unauthorized file access : The PHP code in your web
applications may contain lots of privileged Information or
directions to locate such information i.e.: database user
account information.
• Therefore being able to properly protect your PHP files
from unauthorized viewing is a must.
• If an attacker tries to access a .php file in the server
normally the result will be the processed output of the
code but not the source code itself.
• However if an attacker manages to break into the
DocumentRoot (i.e. htdocs) folder using some attack,
your PHP code will be visible giving out more
information to attack the system further.
2
© 2020 e-Learning Centre, UCSC 3
Handling Vulnerability
What are vulnerabilities
in Web applications?
238
239
PHP Vulnerability Solutions
Data Sanitizing : Sanitizing data input to PHP code means
converting/removing any embedded scripts or HTML content.
• This sanitizing step stops any type of XSS attacks we
explained before.
• Two functions in PHP can help the sanitizing:
1. htmlspecialchars()
2. filter_var()
• htmlspecialchars() : This function detects HTML tags
embedded in a data string and converts the greater-than
and less-than symbols in the tags to the HTML entity codes
> and <. This doesn’t remove the tags from the input
but converts them to normal text.
• filter_var() : The filter_var() function provides a host of
customized filters for finding and sanitizing different types
of data that could potentially cause harm in your PHP
application.
2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions
Data Sanitizing
• htmlspecialchars() function signature is as follows:
htmlspecialchars(string [, flags [,encoding [,double]]])
• By default, the function encodes the following characters:
Ampersand (&), Double quote ("), Single quote ('), Less than
(<), Greater than (>)
• You can pick and choose which of these items the
htmlspecialchars() function converts and which ones it
allows through by specifying one or more flags.
2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions
2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions
Data Sanitizing
• filter_var() function signature is as follows: filter_var(string
[, filter] [, flags])
• The filter and flags parameters are optional, but in most
cases you’ll at least specify the filter to use. The filter
defines what class of characters the filter_var() function
should look for, and the flags parameter fine-tunes subsets
of characters within the filter class.
2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions
Some filter_var() function filter options for sanitizing
Option Description
FILTER_SANITIZE_EMAIL Removes invalid characters from an email
address.
FILTER_SANITIZE_ENCODED Encodes a string to make a valid URL.
FILTER_SANITIZE_MAGIC_QUOTES Escapes embedded quotes.
FILTER_SANITIZE_NUMBER_FLOAT Removes all characters except digits and float
symbols.
FILTER_SANITIZE_NUMBER_INT Removes all characters except digits and
integer symbols.
FILTER_SANITIZE_SPECIAL_CHARS Removes quotes, as well as greater-than,
less-than, and
ampersand characters.
FILTER_SANITIZE_STRING Removes all HTML5 tags.
FILTER_SANITIZE_URL Removes all invalid URL characters.
2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions
2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions
Function Description
is_bool() Returns TRUE if the value is a Boolean data type.
is_float() Returns TRUE if the value is in valid float format.
is_int() Returns TRUE if the value is an integer value.
is_null() Returns TRUE if the value is NULL.
is_numeric() Returns TRUE if the value is in a valid numeric format.
is_string() Returns TRUE if the value is a string as opposed to a
number.
2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions
2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions
2
© 2020 e-Learning Centre, UCSC 4
Web Services
Web Services
“A web service is a software system designed to
support interoperable machine-to-machine
interaction over a network. It has an interface
described in a machine-processable format
(specifically WSDL). Other systems interact with the
web service in a manner prescribed by its description
using SOAP-messages, typically conveyed using HTTP
with an XML serialization in conjunction with other
web-related standards.”
— World Wide Web Consortium, Web Services
Glossary
2
© 2020 e-Learning Centre, UCSC 5
Web Services
2
© 2020 e-Learning Centre, UCSC 5
PHP Web services
• Web service is a remote service that allows clients to use
HTTP protocol to utilize APIs hosted remotely over a
network.
• There are different standards to implement web services
such as SOAP and REST.
• We will use PHP to implement a REST based web service.
• The web service is technologically same as a web
application used by a human but different from it as the
usage is to another program rather than a human.
• Web service can be consumed by any client including
another web service.
2
© 2020 e-Learning Centre, UCSC 5
PHP Web services
• REST or Representational State Transfer is one of the
popular architectural style used to develop web services.
• The objective is to build a RESTful web service in PHP to
provide resource data based on the request with the
network call by the external clients. The steps to create web
service:
1. Create request URI with patterns that follow REST
principles.
2. Make the RESTful service to be capable of responding
to the requests in JSON/ XML or HTML formats.
3. Demonstrate the use of HTTP Status code based on
different scenarios.
4. Demonstrate the use of Request Headers.
5. Test the RESTful web service using a REST client.
2
© 2020 e-Learning Centre, UCSC 5
PHP Web Services
• Basic architecture of a RESTful web service:
2
© 2020 e-Learning Centre, UCSC 5
PHP Web services
• We will create a table and implement HTTP based
web services to perform CRUD operations on the
data in that table.
• The communication with the browser happens
through HTTP protocol similar to viewing a web
page in world wide web.
• The message format used to communicate is JSON
(Java Script Object Notation).
• Both server and client has to agree what types of
messages are supported and their meaning.
2
© 2020 e-Learning Centre, UCSC 5
PHP Web services
• We create a new
databased and a table
to keep the data for
our web service.
• Using phpMyAdmin we
execute the script to
make the necessary
changes to the
database.
2
© 2020 e-Learning Centre, UCSC 5
Activity: MySQL
• We create the database
“rest_web” and table
“user” as given in the
following script.
• Manually insert an entry to
the table with your
information.
• Notice that ID column is
automatically updated.
2
© 2020 e-Learning Centre, UCSC 5
PHP Web services
• To connect to the database we have to repeat
some code which can be in a reusable php script.
• This file is connect.php. We use the technique if
including this file in other places.
2
© 2020 e-Learning Centre, UCSC 5
PHP Web services
• To call the web service use either curl program or a browser
based client
curl
2
© 2020 e-Learning Centre, UCSC 6
PHP Web services
Mozilla
add-on
based
REST
client
2
© 2020 e-Learning Centre, UCSC 6
PHP Web services
2
© 2020 e-Learning Centre, UCSC 6
Activity: PHP Web services
2
© 2020 e-Learning Centre, UCSC 6
PHP Web services
2
© 2020 e-Learning Centre, UCSC 6
PHP Web services
• Following shows the PUT API call processing in PHP.
• This API does an update on our table.
2
© 2020 e-Learning Centre, UCSC 6
PHP Web services
• Notice that we have used some preprocessing code to
use HTTP PUT as PHP does not support direct accessing
the it similar to GET and POST.
2
© 2020 e-Learning Centre, UCSC 6
Activity: PHP Web services
• Complete the below code fragment with the same
approach described before and name it as edit.php.
Access the edit API from client and test the result in
the “rest_web” table.
2
© 2020 e-Learning Centre, UCSC 6
PHP Web services
• Following shows the PUT API call and
response in the client program.
2
© 2020 e-Learning Centre, UCSC 6
Additional Information on PHP
Web Service
• Curl client program : https://curl.se/windows/
• Mozilla REST client :
https://addons.mozilla.org/en-
US/firefox/addon/restclient/
• JSON processing in PHP :
https://www.w3schools.com/js/js_json_php.asp
• PHP Global variables :
https://www.w3schools.com/php/php_supergloba
ls.asp
2
© 2020 e-Learning Centre, UCSC 6