file5
file5
& MySQL
IT3406 – Web Application Development II
Level II - Semester 3
A
ucsc © 2020 e-Learning Centre, UCSC
Topic
• 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)]
Example
<! DOC TYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
<
Try it Yourself »
• 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.
<?php
echo "My first PHP script!";
?>
)
© 2020 e-Learning Centre, UCSC
l
7
PHP Programming with networked server
>
php
ill
m 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
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
String Concatenation Operator
String String +Operator
operand Operator operand
+
1
step l "theopen" "tutorials"
String String
5
© 2020 e-Learning Centre, UCSC
7
Activity: Constants
5
© 2020 e-Learning Centre, UCSC
8
Variables and Operators
A
We can thfnk that
placeholders for 10=2x S variable is one type of
unknown values
w 3
variable
Container where we can
store some element
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): <?php
$x = 5;
$y = 10;
function myTestO {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; }f outputs 15
?>
nyTest();
myTest();
myTest();
6
© 2020 e-Learning Centre, UCSC
9
Arithmetic Operators
•Summary of basic mathematical operators in PHP
** $x ** $y $x to the power of $y
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:
1 <7php
2 = arrayC'Dj” ,"Kamal","de",'"Lanerole");
3 foreach ($person as $value) {
4 $len = strleri($value);
5T swi tch(j>len){
6 case 0:
7 case 1:
8 case 2:
9 echo "shorten" ;
10 breaks
11 case 3:
12 case 4:
13 case 5:
14 echo "medium\n";
15 break ;
16 default:
17 echo "long\n"!
ia }
19 }
20 ?>
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.
<?php
$cars = a may("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ",'. $cars[l] . " and ” . $cans[2] .
?>
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:
<?php
for ($row = 0; $row < 4; $row++) {
echo ,T<pxb>Row number $row</bx/p>";
echo IT<ul>";
for ($col = 0; $col < B; $col++) {
echo "<li>'.$cars[$row][$col].w</li>';
}
echo "</ul>”;
}
?>
V Data processed
Login on the server
[server,php]
--
Email b4<?
IpwpJ
0
$cmaa<>
/A
Message
1
>4 V
r
t
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
The cookie
Wfcat biCootte?
PHPS Cookies
(D
O
2
A HWUi A Ofttn vMHl bo idfi-fllÿr a l#Wf. A CWA* ti 5«taU
Cliff ihjl: th? wrvf r f pn Iftf MMVT qpmptjt«X«H Itin# Ihf *
Hello World! s#*nf compute* «tqucscs 1D»ge wTih 1Um*rvt*r 11 wJI «**1the
Cecftw top. Wrlh P'HP iiHj tjn balls [rrjSr And rrlrwvp [«lw
vakm
Create Cocfcla-i With PHP
(A SivrtM
ID
t*lt*tik*|Ai-fr v&luC, fnfli**-, part\ AMHW', frtutt,
;:Th
© 2020 e-Learning Centre, UCSC
I 1
2
1
© 2020 e-Learning Centre, UCSC 2
Setting a cookie – setcookie()
Syntax: Cookies must be sent
• setcookie($name [, $value before producing any
[, $expire]]); output in a script. This
Semantic: requires
• Sends a cookie to the browser. setcookie()
• $name - The name of the cookie function to be used
• $value – The value of the cookie prior to any output,
• $expire – The time (in seconds) the including <html> and
cookie expires. If this value is set to <head> tags as well as
0 or omitted, the cookie will expire
when the browser closes.
any whitespace.
• The function returns the Boolean
value TRUE on success or FALSE
on failure.
1
© 2020 e-Learning Centre, UCSC 2
Checking whether cookies are
enabled or not
<?php
setcookie("name","saman",time()+3600);
if(count($_COOKIE) > 0){
echo "Cookies are enabled<br>";
} else {
echo "Cookies are disabled <br>";
}
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
Create
±
-c
fopcnQ fd«e()
Open Close
Pile
frcod()
Handling fwritcQ
in Phjs
Read Write
pcngmcQ
Rename A unlinkfi
Delete
File Handling
W writing(writing to a file)
r reading(reading to a file)
a append(adding to a file)
130
Typical operations on files
• Opening a file
• Adding data https://www.youtube.com/watch?v=RgOVVV9GAXQ
• 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
Local SMTP Local queue Recipient mailbox
I
SMTP Pickup Destination queue
v
PHP script MTA > Destination SMTP
H mail
Direct
1 C7php
2 i/ the message
3 $msg = "This is a \n Test Message\nThaank you!11;
4
5 // use wordwrapO if lines are longer than 70 characters
6 $msg = wordwrap($msg,7Q)
7
6 // send email
9 [nail("abc@abc. net" r "Test Message" f$msg);
10 ?>
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
I
Single Inheritance Hierarchical Inheritance
f /-
Multilevel Inheritance
gp nu |
|
I
/\
a
Building classes by inheritance
Simple Hierarchical
Inheritance Inheritance Multilevel
Inheritance
[ 1
IHTL
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
comments.
1
4
5
6»
7
cTphp
__
• Complete the PHP class given below according to the
2 * class Fruit {
3 public $name‘,
public $color; //default color is "green"
function construct($nanne) {
$this->name = $name;
_
6 }
9
10 public function setColor(ÿc) {//update the color variable
11 }
12
13 * function destructQ {
14 echo "The fruit is {$this->name}.\n" ;
15 }
16
17 public function to5tring(){ //return "color-name";
ia }
19 }
20
21 $applel = new Fruit(’"Apple") ;
22 $apple2 = new Fruit("Apple");
23 $applel-> destruct();
24 $orangel = new Fruit("Qrange");
25 echo $orangel,"\n" ;
2& $orangel->setColor('ryellow") ;
27 echo $apple2,"\n" ,$orangel ,”\n" ;
26 7>
_
1
3
4
5
6*
7
a
9
10 *
11
12
13
14 T
15
16
17
10 *
C7php
2 * class Fruit {
}
function
}
_
public $narme;
public $color = "green";
construct($name) {
$thi s->name = £nanne;
function destruct() {
echo "The fruit is {$this->name}.In" ;
I
29 echo $apple2,$orangel ;
30 ?> 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
?>
© 2020 e-Learning Centre, UCSC
I
1
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?
Buffer
Overflows
Insecure
Insecure
Conffg.
Storage
Mgnt
Unvalidated
CSS Flaws
Input
Broken
Denial of Authen
Service iession Mgnl
Injection Broken
Flaws Improper Access
Error Control
Handling
238
WEB APPLICATION
ATTACKER
C2>
4
a
©
HASH CRACK PASSWORD HASH
ADMIN LOGIN
< PHP BACKDOOR INJECTION
# ++ #+ + ++ +
A
SERVER SERVER
V
ATTACKER
>.
I
M
PRIVILEGE ESCALATION
www-data root
A
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
WSDL (Web Services Description Language) is an XML-based language used to describe the functionality offered by a web
service. It defines how web services can be called, what parameters they expect, and what data they return, enabling
communication between different systems over a network. Here’s a breakdown of key elements of WSDL:
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:
RESTful
Web Service
8
© 2020 e-Learning Centre, UCSC
I
2
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 1
databased and a table 2
3
— Database: 'rest web'
create database IF NOT EXISTS 'rest web'
to keep the data for 4
5
our web service. 6
7
— Table structure for table 'user'
CREATE TABLE IF NOT EXISTS "user" (
6 "ID' int(ll) NOT NULL AUTO_INC REMENT ,
• Using phpMyAdmin we 9
IQ
'name' tent NOT NULL,
'email" varchar(10O) NOT NULL,
execute the script to 11
12
"password1 varchar(lQQ) NOT NULL,
'status' text NOT NULL,
make the necessary 13
14
PRIMARY KEY (ID')
) AUTO_ INCREMENTS ;
changes to the 15
database.
2
© 2020 e-Learning Centre, UCSC 5
Activity: MySQL
• We create the database 1
2 — Database: 'rest web'
“rest_web” and table 3 create database IF NOT EXISTS 'rest web'
4
“user” as given in the 5
following script. 6
7
— Table structure for table 'user'
CREATE TABLE IF NOT EXISTS "user" (
6 "ID' int(ll) NOT NULL AUTO_INC REMENT ,
• Manually insert an entry to 9 'name' tent NOT NULL,
IQ 'email" varchar(10O) NOT NULL,
the table with your 11 "password1 varchar(lQQ) NOT NULL,
'status' text NOT NULL,
information. 12
13 PRIMARY KEY (ID')
14 ) AUTO_ INCREMENTS ;
• Notice that ID column is 15
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.
credentials(usern 6
7 [// Create connection
16 ?>
inserts to database. 14
15
$qur = mysqli_query($conn ,$sql);
if($qur){
16 $json = array("status" => 1, "msg" => "Done User added!");
• Returns a JSON 17 *
18
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
response to the 19
20
}
}else{
caller 21
22 }
$json = array("status" => 0, "msg" => "Request method not accepted");
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
= array();
if(!$qur){
$]son = array("status" => 0, "msg" => "User ID not define ".$uid );
}else{
while($row = mysqli_fetch_array($qur)){
= array("name" => $row[ 1 name 1], "email" => $row" ' email'], status' => £row['status ]);
1
}
$j son = array("status" => 1, "info" =>
}
}else{
I
$json = array("status" => 0, "msg” => "User ID not define ".$uid);
}
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.
5 T -if($_SERVER[,REQUEST_METHOD'] == "PUT"}{
6 $params = ArrayO I
7 parse_str(file_get_contents('php :/ /input1 ), $pararas);
a $G LQ BAL5["_ PUT"] = $params;
9 // Add these request vars into _REQUEST, mimicing default behavior,
10 //PUT/DELETE will override existing COOKIE/GET vars
li $_REQUE5T = $params + $_REQUE5T;
12
13 $uid = isset($_PUT[ uid ']) ? htmlspecialchars($_PUT“ 1 uid 1]) : II II
14 $status = isset($_PUT] 1 status ]) 7 htmlspecialchars($_PUT['status']) : II II
15 !i Add your validations
16 * if( iempty($uid)){
17 $qur = mysqli _query($conn ,
18 "UPDATE ' rest_web' . 'user1 SET 'status'='Jstatus 1 WHERE 'user'.'ID' ='$uidr;");
19 » if($qur){
20 $json = array(nstatus" => 1, "msg" => "Status updated!!.11);
21 » }else{
22 $json = a rray("status" =s 0, "msg” => "Error updating status"};
23 }
24 » }el5e{
25 $json = array("status" =5 0, "msg” => "User ID not define 1"};
26 }
27 T }else{
2a
29 }
$json = array("status" == 0, "msg” => "User ID not define 21’};
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
2 : Fundamentals of Asynchronous
JavaScript and XML (AJAX)
IT3406 – Web Application Development II
Level II - Semester 3
1 Enter
URL \
Look up
2 the IF
:
3 Request
mein page
4 Receive
request :
5 :
Fetch
page
6 Contains
PHP 1
Process
7 PHP :
8 Execute
: SQL
Receive
9 data
Return
10 page
11 Display
page
• A scripting language,
• Speedy and seamlessly integrating with HTML code.
W index.php
1 < !DOCTYPE html>
2 <html>
3 <body>
4 v <?php
5 echo "Hello World. Today is ".date("1").".
6 ?>
7 How are you?
8 </body>
9 </html>
• Modify HTML on the fly | Process a credit card | Add user details
to a database | Fetch information from a third-party website |
etc.…..
• What are the alternatives for PHP for server side scripting?
• Compare and contrast advantages and disadvantages of the
alternatives and PHP.
• In early days,
• Developers used ‘flat’ text files to store data:
• usernames, passwords etc..
• Popularity of MySQL…
• Free to use and installed on vast numbers of Internet web
servers.
• Robust and exceptionally fast database management system
that uses English-like commands. Example:
1
© 2020 e-Learning Centre, UCSC
0
Activity
1
© 2020 e-Learning Centre, UCSC
1
JavaScript
Hello World. Today is Tim Dec 31 2020 16:24:57 GMT+0530(India Standard Time)How are yon?
1
© 2020 e-Learning Centre, UCSC
3
JavaScript contd.
1
© 2020 e-Learning Centre, UCSC
4
Activity
1
© 2020 e-Learning Centre, UCSC
5
CSS
1
© 2020 e-Learning Centre, UCSC
6
PHP + MySQL + JavaScript + CSS ?
1
© 2020 e-Learning Centre, UCSC
7
Asynchronous JavaScript and XML
(AJAX)
Asynchronous communication?
• Google maps: an example for asynchronous communication in web
applications.
• New sections of a map are downloaded from the server when
needed, without requiring a page refresh.
1
© 2020 e-Learning Centre, UCSC
9
Asynchronous communication?
• Results in,
• Improved user interfaces | Better responsiveness
• Examples;
• Updating content of a web page without reloading the page.
• Form auto-completion and in-line validation.
• Social networks – reacts, ratings, voting, polls, etc..
• Chat rooms and instant messaging
2
© 2020 e-Learning Centre, UCSC
0
AJAX introduction
2
© 2020 e-Learning Centre, UCSC
1
AJAX contd.
Source: https://www.w3schools.com/xml/ajax_intro.asp
2
© 2020 e-Learning Centre, UCSC
2
XMLHttpRequest object
2
© 2020 e-Learning Centre, UCSC
3
XMLHttpRequest object methods
2
© 2020 e-Learning Centre, UCSC
4
XMLHttpRequest object properties
2
© 2020 e-Learning Centre, UCSC
5
Example: Asynchronous program
2
© 2020 e-Learning Centre, UCSC
6
Example: Asynchronous program contd.
Click event
2
© 2020 e-Learning Centre, UCSC
7
Example: Asynchronous program contd.
• send()
• Sends the request to the server
2
© 2020 e-Learning Centre, UCSC
8
Example: Asynchronous program contd.
• GET or POST?
• GET is simpler and faster than POST.
• Some browsers may cache GET requests, whereas POST requests
will never be cached.
• When cached, the browser would just redisplay what it got previously
rather than displaying fresh input.
• Solution: adds a random parameter to each request, ensuring
that each URL requested is unique.
2
© 2020 e-Learning Centre, UCSC
9
Activity
Change the given sample code so that you can resolve the
cached result issue in GET requests. Add a unique ID to the
URL.
3
© 2020 e-Learning Centre, UCSC
0
Activity
3
© 2020 e-Learning Centre, UCSC
1
Example: Asynchronous program contd.
• The url
• Can be a file on the server.
• .txt, .xml, .php etc...
• Asynchronous
• True or False?
• If set true, server requests would be sent asynchronously.
3
© 2020 e-Learning Centre, UCSC
2
Example: Asynchronous program contd.
• onreadystatechange property
• Defines a function to be called when the readyState property
changes.
• readyState property
• Holds the status of the XMLHttpRequest.
3
© 2020 e-Learning Centre, UCSC
3
Example: Asynchronous program contd.
• status property
• Holds the status of the XMLHttpRequest object
• 200: "OK“ | 404: "Page not found“ etc..
3
© 2020 e-Learning Centre, UCSC
5
Example: Asynchronous program contd.
• Then its innerHTML property is assigned the value that was returned by
the call.
• Element of the web page changes, while everything else remains the
same.
• responseText - get the response data as a string.
3
© 2020 e-Learning Centre, UCSC
6
XML
3
© 2020 e-Learning Centre, UCSC
7
Activity
3
© 2020 e-Learning Centre, UCSC
8
XML vs HTML
• XML is extensible.
• Most XML applications will work as expected even if new data is
added or removed.
3
© 2020 e-Learning Centre, UCSC
9
Activity
4
© 2020 e-Learning Centre, UCSC
0
XML DOM
Source: https://www.w3schools.com/xml/xml_dom.asp
4
© 2020 e-Learning Centre, UCSC
1
XML DOM contd.
4
© 2020 e-Learning Centre, UCSC
2
XML DOM contd.
4
© 2020 e-Learning Centre, UCSC
3
4
© 2020 e-Learning Centre, UCSC
4
4
© 2020 e-Learning Centre, UCSC
5
Activity
• Write the code to display the XML file you wrote in the
previous assignment in a web page.
• Each element needs to be displayed.
4
© 2020 e-Learning Centre, UCSC
6
4
© 2020 e-Learning Centre, UCSC
7
4
© 2020 e-Learning Centre, UCSC
8
4
© 2020 e-Learning Centre, UCSC
9
Activity
5
© 2020 e-Learning Centre, UCSC
0
JSON
5
© 2020 e-Learning Centre, UCSC
1
Activity
5
© 2020 e-Learning Centre, UCSC
2
JSON vs XML
• Both are,
• Human readable
• Hierarchical
• Can be parsed and used by lots of programming languages
• Can be fetched with an XMLHttpRequest
• Different because,
• JSON does not have end tags
• Shorter
• Quicker to read and write
• Can use arrays
• JSON is much easier to parse than XML
5
© 2020 e-Learning Centre, UCSC
3
5
© 2020 e-Learning Centre, UCSC
4
5
© 2020 e-Learning Centre, UCSC
5
Activity
5
© 2020 e-Learning Centre, UCSC
6
JSON contd.
• JSON.parse()
• When receiving data from a web server, the data is always a string.
• Parse the data with JSON.parse(), and the data becomes a
JavaScript object.
• JSON.stringify()
• When sending data to a web server, the data has to be a string.
• Convert a JavaScript object into a string with JSON.stringify()
5
© 2020 e-Learning Centre, UCSC
7
AJAX and PHP
5
© 2020 e-Learning Centre, UCSC
8
5
© 2020 e-Learning Centre, UCSC
9
Version controlling
60
Version controlling
6
© 2020 e-Learning Centre, UCSC
1
Git
6
© 2020 e-Learning Centre, UCSC
2
Setting up Git
6
© 2020 e-Learning Centre, UCSC
3
Activity
6
© 2020 e-Learning Centre, UCSC
4
Configuring Git
• Setting up identity
• The first thing you should do when you install Git is to set your
user name and email address.
• This is important because every Git commit uses this
information, and it’s immutably baked into the commits you
start creating.
$ git config --global user.name "John Doe"
$ git config --global user.email [email protected]
• To verify your configurations,
$ git config user.name
$ git config user.email
6
© 2020 e-Learning Centre, UCSC
5
Initializing a repository
• To create your first Git repository , you will simply use the
git init command.
• This will initialize an empty Git repository in your source
code directory.
6
© 2020 e-Learning Centre, UCSC
6
Initial commit
6
© 2020 e-Learning Centre, UCSC
7
Initial commit contd.
6
© 2020 e-Learning Centre, UCSC
8
Initial commit contd.
6
© 2020 e-Learning Centre, UCSC
9
Staging changes
• Let us change the README first and check the git status.
• It shows that our README was modified, but that it’s not
staged for commit yet. We do this by using the git add
command.
7
© 2020 e-Learning Centre, UCSC
0
Viewing history
7
© 2020 e-Learning Centre, UCSC
1
Ignoring specific files
7
© 2020 e-Learning Centre, UCSC
2
Activity
7
© 2020 e-Learning Centre, UCSC
3
Removing files
7
© 2020 e-Learning Centre, UCSC
4
Removing files
7
© 2020 e-Learning Centre, UCSC
5
Removing files
7
© 2020 e-Learning Centre, UCSC
6
Branching & merging
• Allows you to separate various segments of changes to
your code into sub-repositories.
• Branching
• When you want to add a new feature or fix a bug, you may
spawn a new branch to encapsulate your changes.
• Makes it harder for unstable code to get merged into the main
codebase.
7
© 2020 e-Learning Centre, UCSC
7
Branching & merging contd.
• Merging
• Lets you take the independent lines of development created by
git branch and integrate them into a single branch.
• Ex: we have a new branch feature that is based off the master
branch. We now want to merge this feature branch into master.
7
© 2020 e-Learning Centre, UCSC
8
Branching & merging contd.
7
© 2020 e-Learning Centre, UCSC
9
Branching & merging contd.
8
© 2020 e-Learning Centre, UCSC
0
Branching & merging contd.
• To delete a branch:
8
© 2020 e-Learning Centre, UCSC
1
Other features in Git
• Stashing Changes
• Tagging
• Lightweight tags
• Annotated tags
• Undoing changes
• Amend
• Un-stage
• File Reset
• Soft Reset
• Mixed Reset
• Hard reset
8
© 2020 e-Learning Centre, UCSC
2
Activity
8
© 2020 e-Learning Centre, UCSC
3
Activity
8
© 2020 e-Learning Centre, UCSC
4
Activity
8
© 2020 e-Learning Centre, UCSC
5
Version control in cloud
8
© 2020 e-Learning Centre, UCSC
6
PHP Coding Standards
Introduction to coding standards
• PHP-FIG
• PHP Framework Interoperability Group
• created a standards body for PHP frameworks.
8
© 2020 e-Learning Centre, UCSC
8
Basic coding standards - Files
• PHP Tags
• PHP code must use <?php tags or the short echo tag in <?=
format.
• No other tag is acceptable, even if you have short tags enabled
in your PHP configuration.
8
© 2020 e-Learning Centre, UCSC
9
Basic coding standards - Files
• Side Effects
• PHP file should either declare new symbols (classes, functions,
constants, etc.) or execute logic with side effects, but never
both.
• Side effects - logic executed without directly relating to declaring
a class, functions or methods, constants, etc.
• Unlike the following example, a file shouldn’t both declare a
function AND execute that function.
9
© 2020 e-Learning Centre, UCSC
0
Basic coding standards – Name spaces and class
names
9
© 2020 e-Learning Centre, UCSC
1
Basic coding standards – Class constants, Properties,
and Methods
• Constants
• Class constants must be declared in all uppercase using
underscores as separators.
• Properties
• Property names: $StudlyCaps , $camelCase , or $under_score
• Can mix them if they are outside of the scope of each other.
• Be consistent within that given scope.
• Better to stick to one throughout all of your code.
• More uniformity and readability.
9
© 2020 e-Learning Centre, UCSC
2
Basic coding standards – Class constants, Properties,
and Methods
• Methods
• Must be declared using camelCase()
9
© 2020 e-Learning Centre, UCSC
3
Coding style – General
• Files
• All PHP files must use the Unix linefeed line ending, must end with
a single blank line, and must omit the close ?> tag if the file only
contains PHP.
• Lines
• There must not be a hard limit on the length of a line.
• There must be a soft limit of 120 characters.
• Lines should not be longer than 80 characters, and should be split
into multiple lines if they go over 80 characters.
• There must not be trailing whitespace at the end of non-blank lines.
• Blank lines may be added to improve readability and to indicate
related blocks of code.
• You can only have one statement per line.
9
© 2020 e-Learning Centre, UCSC
4
Coding style – General
• Indentation
• You must use four spaces and never use tabs.
• (Most IDEs can map spaces to tab key.)
9
© 2020 e-Learning Centre, UCSC
5
Coding style – Namespace and Use declarations
9
© 2020 e-Learning Centre, UCSC
6
Coding style – Classes, Properties, and Methods
• Classes
• The extends and implements keywords must be declared on the
same line as the class name.
• The opening brace for the class must go on its own line, and the
closing brace must appear on the next line after the body of
your class.
• Lists of implements may be split across multiple lines, where
each subsequent line is indented once.
• When doing this, the first item in the list must appear on the next line, and
there must only be one interface per line.
9
© 2020 e-Learning Centre, UCSC
7
Coding style – Classes, Properties, and Methods
• Properties
• Visibility (public, private, or protected) must be declared on all
properties in your classes.
• The var keyword must not be used to declare a property.
• There must not be more than one property declared per
statement.
• Property names should not be prefixed with a single underscore
to indicate protected or private visibility.
9
© 2020 e-Learning Centre, UCSC
8
Coding style – Classes, Properties, and Methods
• Method arguments
• In your method argument list, there must not be a space before
each comma, but there must be one space after each comma.
• Method arguments with default values must go at the end of
the argument list.
• Can split method argument lists across multiple lines, where
each subsequent line is indented once.
• When using this approach, the first item in the list must be on the next
line, and there must be only one argument per line
• If the split argument list is used, the closing parenthesis and the
opening brace must be placed together on their own line with
one space between them.
9
© 2020 e-Learning Centre, UCSC
9
Coding style – Classes, Properties, and Methods
1
© 2020 e-Learning Centre, UCSC 0
Coding style – Control structures
1
© 2020 e-Learning Centre, UCSC 0
Coding style – Control structures
1
© 2020 e-Learning Centre, UCSC
0
2
Coding style – Control structures
• switch, case
• The case statement must be indented once from the switch
keyword, and the break keyword or other terminating keyword (
return, exit, die , etc.) must be indented at the same level as the
case body.
• There must be a comment such as // no break when fall-through is
intentional in a non-empty case body.
1
© 2020 e-Learning Centre, UCSC
0
3
Coding style – Control structures
• while, do while
• These structures place the braces and spaces similarly to those in
the if and switch structures
1
© 2020 e-Learning Centre, UCSC
0
4
Coding style – Control structures
• for
• Standards comply to the following examples.
1
© 2020 e-Learning Centre, UCSC 0
Coding style – Control structures
• foreach
• Unlike in the for statement, the space is required if you are
separating the key and value pairs using the => assignment.
1
© 2020 e-Learning Centre, UCSC 0
Coding style – Control structures
1
© 2020 e-Learning Centre, UCSC 0
PHP CodeSniffer
An example for errors that were detected when validating against the PSR-1 and
PSR-2 standards using PHP CodeSniffer 1
0
© 2020 e-Learning Centre, UCSC
9
phpDocumentor
1
© 2020 e-Learning Centre, UCSC 1
Frameworks for Web Development
Why use frameworks?
• Laravel 5
• Symfony 2
• Zend Framework 2
• CodeIgniter
1
© 2020 e-Learning Centre, UCSC
1
3
END
3. Advanced Client Side Development
<SCRIPT>
• Eg:
JavaScript code goes here ..
</SCRIPT>
<script type="text/javascript">
IMPORTANT:
• When you run the test, your browser may not run the
JavaScript code or it may prompt you to allow the code
to run.
• Some browsers have built-in security features to block
running JavaScript code embedded in a web page.
• You’ll need to consult your browser documentation on
how to enable JavaScript code.
1
© 2020 e-Learning Centre, UCSC
0
Example for embedded code in
the <HEAD> section
<!DOCTYPE html>
<html>
<head>
<title>Testing JavaScript in the Head Section</title>
<script>
alert(“This executes before loading the content.");
</script>
</head>
<body>
<h1>This is the web page</h1>
</body>
<html>
1
© 2020 e-Learning Centre, UCSC
1
Embed JS in the <BODY> tag
<!DOCTYPE html>
<html>
<head>
<title>Testing JavaScript in the Body Section</title>
</head>
<body>
<h1>This is before executing the JS code</h1>
<script>
alert("This is the JavaScript program!");
</script>
<h1>This is after executing the JS code</h1>
</body>
<html>
1
© 2020 e-Learning Centre, UCSC
2
Compare the output
Best Practice
1
© 2020 e-Learning Centre, UCSC
3
Option 02: Using external JS file
Usage:
• Using an external file is a good design aspect when
the same code repeatedly applicable to many
number of web pages.
• Keeping the repeating JS code separately improves
maintainability of the code.
<script src=“javascript_code.js"></script>
1
© 2020 e-Learning Centre, UCSC
4
Variables in JavaScript
1
© 2020 e-Learning Centre, UCSC
5
Variables in JavaScript
• Variable holds data temporarily in the memory
until a program complete its execution.
• These temporary data storage locations help
manipulating data, retrieving data at later stages
and displaying it to the user.
1
© 2020 e-Learning Centre, UCSC
6
Rules for defining JS variables
Remember to adhere following rules when defining
variables.
1
© 2020 e-Learning Centre, UCSC
7
Declare and initialize a variable
• Use var keyword to declare the variable
• Give a meaningful name (best practice)
• Now you can initialize the variable using a value
Example: var name; name = “Kamal”;
1
© 2020 e-Learning Centre, UCSC
8
JavaScript Data Types
1
© 2020 e-Learning Centre, UCSC
9
JavaScript data types
Basic data types
2
© 2020 e-Learning Centre, UCSC
0
JavaScript basics
Arrays
• Arrays allow us to store a list of items into a single
variable.
• For example:
var marks = [80, 50, 65];
• Individual items are called elements of the array.
• Using the index of the element, the value can be
extracted.
• Syntax: marks[1] will give the number 50.
2
© 2020 e-Learning Centre, UCSC
1
JavaScript operators for data
manipulation
2
© 2020 e-Learning Centre, UCSC
2
JavaScript mathematical
operators
2
© 2020 e-Learning Centre, UCSC
3
JavaScript Boolean operators
2
© 2020 e-Learning Centre, UCSC
4
Program flow control structures
2
© 2020 e-Learning Centre, UCSC
5
Program flow control structures
• Flow control structures are used to alter the default
flow of code execution in a JavaScript program.
• These structures contain conditional statements
from which a certain condition is evaluated.
• Depending on the result of the evaluation, the
program would execute the code.
2
© 2020 e-Learning Centre, UCSC
6
Program flow control structures
• Conditional statements
• If block
• If else block
• Switch statement
• Loops
• Do.. While
• While
• For
• For.. In
2
© 2020 e-Learning Centre, UCSC
7
if statement
• The condition is evaluated whether true or false.
• The code inside the block only executes if the
condition is evaluated as true.
if (condition) { if (5>2) {
code goes here… alert(“success”);
} }
2
© 2020 e-Learning Centre, UCSC
8
else statement
• With the if statement, if the condition is not met,
the interpreter just skips the code you specify in
the code block.
• The else statement allows you to specify code to
run if the condition evaluates to a false value.
if (type == “Lory”) {
message = “Sorry, you are not allowed to park here”;
status = “failed”;
} else {
message = “You may begin the game”;
status = “success”;
}
2
© 2020 e-Learning Centre, UCSC
9
switch statement
• Switch statement is
similar to the else if switch (expression) {
statement. case match1:
• JavaScript interpreter statements
evaluates the expression break;
and the result will be case match2:
matched against the statements
case statement. break;
• break statement breaks default:
the flow and exits from statements
the block. }
3
© 2020 e-Learning Centre, UCSC
0
switch statement contd..
• Each case statement specifies a different possible
result of the expression.
• If there is a match, the interpreter runs the
statements contained in that section.
• The break statement forces the interpreter to skip
over the remaining case statement sections.
• If none of the case results matches, the interpreter
runs the statements under the default statement.
3
© 2020 e-Learning Centre, UCSC
1
Loops in JavaScript
• When the same block of code runs multiple times,
it is called a loop.
• Typically, one or more variables changes values in
each iteration of the loop .
• Loop ends once a specific criteria meets.
3
© 2020 e-Learning Centre, UCSC
2
Loops in JavaScript
• JavaScript supports several looping structures as
shown in the table below,
3
© 2020 e-Learning Centre, UCSC
3
The do… while loop
• Do while loop executes the first iteration without
checking a condition.
• Do while loop executes at least once.
• At the end of the block, it tests a condition to
determine whether to repeat or not.
3
© 2020 e-Learning Centre, UCSC
4
The do… while loop syntax
do
{
statements..
}
while (condition);
3
© 2020 e-Learning Centre, UCSC
5
The do… while loop flowchart
3
© 2020 e-Learning Centre, UCSC
6
The while loop
• while loop acts opposite to the do.. while loop
• While loop checks the condition at the very
beginning
• None of the iterations would continue without
evaluating the condition
3
© 2020 e-Learning Centre, UCSC
7
The while loop syntax
3
© 2020 e-Learning Centre, UCSC
8
The while loop flowchart
3
© 2020 e-Learning Centre, UCSC
9
The for loop syntax
Variable to be
changed in each
iteration
4
© 2020 e-Learning Centre, UCSC
0
The for loop flowchart
4
© 2020 e-Learning Centre, UCSC
1
The for.. in loop
• The for...in loop helps to iterate over an array of
which the number of values are not certain
• It executes till the end of the array extracting
individual data values per iteration
• The for...in statement ends when it runs out of data
elements in the array
• Elements are accessed based on the respective
index in the array
4
© 2020 e-Learning Centre, UCSC
2
The for.. in loop syntax
4
© 2020 e-Learning Centre, UCSC
3
JavaScript functions
4
© 2020 e-Learning Centre, UCSC
4
What is a functions
• A function is a block of organized, reusable code
that is used to perform a single action
• If we have a code segment (complex/simple)
repeats over and over in different places, we can
write a function and reuse the function without
repeating the same code chunk
• Functions make the code simple and maintainable
4
© 2020 e-Learning Centre, UCSC
5
Syntax of a JavaScript function
4
© 2020 e-Learning Centre, UCSC
6
JavaScript functions
• Return Type:
• If a function returns a value, the type of the
returning value becomes the return type of
the function
• If it does not return the keyword void is used
• Function Name:
• The function name and the parameter list
together forms the signature of the function
• Name is important for calling the funtion
4
© 2020 e-Learning Centre, UCSC
7
JavaScript functions
• Parameter List:
• A parameter is like a placeholder.
• Parameters/arguments have a type, order and
number of parameters
• Parameters are optional and a function can be
defined without any parameters
• Function Body:
• The function body contains a code block to
perform the task
4
© 2020 e-Learning Centre, UCSC
8
How to use functions
• JavaScript functions are called using the name of
the function and passing the relevant parameters
• For example;
var result = add_values(5,3);
Here, the result variable will store the value 8 after
calling the add_values() function
4
© 2020 e-Learning Centre, UCSC
9
Summary
• JavaScript is a language which can be used to
manipulate front-end dynamic behavior.
• Variables are used to store data temporarily to
support executing the program in memory.
• Data types specify which kind of data cab ne stored
in a particular variable.
• JavaScript operators help in manipulating data on
variables.
• Mathematical and Boolean operators are two
broader categories of operators.
5
© 2020 e-Learning Centre, UCSC
0
Summary
• JavaScript flow control statements are used to alter
the program execution flow.
• Conditional statements and looping structures help
mainly in flow controlling.
• JavaScript functions can be used to reuse code and
improve maintainability.
5
© 2020 e-Learning Centre, UCSC
1
3.2 Document Object Model
(DOM)
IT3406 – Web Application Development II
5
© 2020 e-Learning Centre, UCSC
2
Lesson Outline
5
© 2020 e-Learning Centre, UCSC
3
Introduction to DOM
5
© 2020 e-Learning Centre, UCSC
4
Document Object Model
• HTML document has a number of elements.
• DOM helps finding and locating these elements in a
standard way.
• DOM provides a hierarchical tree structure of
elements.
• By traversing through the tree structure, one can
reach the desired element.
5
© 2020 e-Learning Centre, UCSC
5
DOM tree structure
• Start of the tree structure is always html element
5
© 2020 e-Learning Centre, UCSC
6
DOM tree structure contd..
• Under the top/root element all the other elements
are referred to as child nodes.
• In the html document head comes first and it is
named as first child of the html element.
• body comes after the head and it is named as
second child of the html element.
5
© 2020 e-Learning Centre, UCSC
7
Example code
Source: w3shools
5
© 2020 e-Learning Centre, UCSC
8
DOM tree
5
© 2020 e-Learning Centre, UCSC
9
JavaScript and DOM
• The browser uses the DOM tree to keep track of all
the HTML5 elements, their content, and the styles
on the web page
• JavaScript has full access to the DOM tree created
by the browser as it also works in the client side
• JavaScript is capable of modifying the DOM
hierarchy
• This capability of modifying the DOM helps to add
dynamic nature to the front end of the web
applications
6
© 2020 e-Learning Centre, UCSC
0
JavaScript and DOM
• JavaScript treats each element in DOM as an object
• Objects have Properties and Methods
6
© 2020 e-Learning Centre, UCSC
1
JavaScript and DOM
property
6
© 2020 e-Learning Centre, UCSC
2
Document object properties
6
© 2020 e-Learning Centre, UCSC
3
Document object methods
6
© 2020 e-Learning Centre, UCSC
4
JavaScript DOM objects
• Previous slides describe the document properties
and methods.
• Apart from that, JavaScript also has properties and
methods that apply to each element object in the
document.
• These properties and methods can be used to
expand the capabilities of JavaScript when
interacting with the DOM elements.
6
© 2020 e-Learning Centre, UCSC
5
JavaScript DOM object properties
6
© 2020 e-Learning Centre, UCSC
6
JavaScript DOM object methods
6
© 2020 e-Learning Centre, UCSC
7
JavaScript DOM object methods
6
© 2020 e-Learning Centre, UCSC
8
Finding elements using JS objects
Challenge:
• As your web pages become more complicated, it
may contain possibly thousands of elements
• Finding a specific element and changing or
modifying it will be a real challenge
• Two different ways to find an element
• Using a unique feature assigned to the element to jump
directly to it
• navigate your way down to the element's object from a
specific point in the DOM tree
6
© 2020 e-Learning Centre, UCSC
9
Use element id to find an element
• Assign the element a unique id attribute value
• Reference the elements in your JavaScript code by
using the getElementById() method
7
© 2020 e-Learning Centre, UCSC
0
Walking the tree to find element
• Different properties of child elements can be used
to search for an element in DOM hierarchy,
• Use the firstChild property
• Use the nextSibling property
• We can alternatively use firstChild, lastChild,
nextSibling, or previousSibling properties to reach
wherever we want in the page.
7
© 2020 e-Learning Centre, UCSC
1
Working with form data
• JavaScript objects are capable of accessing the
content of form elements.
• For example, Text boxes, Text Areas, Check boxes
and radio buttons.
• Let us look at how JavaScript uses DOM tree to
access and work with form elements.
7
© 2020 e-Learning Centre, UCSC
2
Text Box
• Use the value attribute of the object to read any
text that may already be in the text box.
• Accessing data in a text box
7
© 2020 e-Learning Centre, UCSC
3
Text Box DOM properties
7
© 2020 e-Learning Centre, UCSC
4
Text Area
• For text area elements also we use value property.
• Same as we did for text box except few unique
DOM properties,
• cols: Sets or retrieves the number of columns
assigned to the text area
• rows: Sets or retrieves the number of rows
assigned to the text area
• wrap: Sets or retrieves whether text can auto-wrap
within the text area
7
© 2020 e-Learning Centre, UCSC
5
Check Boxes
• Check box is used to capture whether a particular
option is selected or not.
• In order to check the condition we can use DOM
checked property.
Example:
7
© 2020 e-Learning Centre, UCSC
6
Checkbox DOM properties
7
© 2020 e-Learning Centre, UCSC
7
Radio buttons
• Working with radio buttons is always a complicated
matter.
• All the radio buttons in the same group use the
same name property.
• Browser handles them as a group.
• Only one radio button in the group can be selected
at any time.
• Handling data from a radio button requires using
the checked and value object properties.
7
© 2020 e-Learning Centre, UCSC
8
3.3 : Asynchronous JavaScript and
3.3 : Asynchronous JavaScript and XML
XML (AJAX)
(AJAX)
IT3406 – Web Application Development II
• Introduction to AJAX
• Establishing connection to server
• XMLHttpRequest class methods
• XMLHttpRequest class properties
• Caching and AJAX
8
© 2020 e-Learning Centre, UCSC
0
Introduction to AJAX
8
© 2020 e-Learning Centre, UCSC
1
Asynchronous JavaScript and XML
• AJAX combines several existing web languages and
standards.
• AJAX helps to produce dynamic content on a web
page.
8
© 2020 e-Learning Centre, UCSC
2
Technologies associated with
AJAX
• JavaScript
• Server side scripting language (PHP,JSP, etc..)
• Extensible Markup Language (XML)
• HTML and CSS
• Document Object Model (DOM)
8
© 2020 e-Learning Centre, UCSC
3
Putting everything together
8
© 2020 e-Learning Centre, UCSC
4
Putting everything together
Step 01: JavaScript communicates with Web server
Step 02: Web server runs PHP program
Step 03: PHP program sends data through XML
Step 04: JS uses HTML and CSS for styling and
positioning data
Step 05: JavaScript uses DOM to place data in the
web page
8
© 2020 e-Learning Centre, UCSC
6
XMLHttpRequest class methods
8
© 2020 e-Learning Centre, UCSC
7
Methods defined in
XMLHttpRequest object class
Following methods support in establishing and
communicating between JavaScript and server.
8
© 2020 e-Learning Centre, UCSC
8
Establishing the connection
• Use open() method to define connection between
browser and server.
• send() method of the XMLHttpRequest object
sends the request to the server.
8
© 2020 e-Learning Centre, UCSC
9
Parameters of open() method
Parameter 1:
• Specifies the method (GET or POST)
Parameter 2:
• The URL to send the request to
Parameter 3:
• Specifies the connection type (Synchronous or
Asynchronous)
Synchronous : Waits till response arrives to continue
Asynchronous: Does not wait till the response
9
© 2020 e-Learning Centre, UCSC
0
Difference of using GET and POST
• GET: Parameters of the request are added to the
URL itself
9
© 2020 e-Learning Centre, UCSC
1
XMLHttpRequest class properties
9
© 2020 e-Learning Centre, UCSC
2
XMLHttpRequest class properties
9
© 2020 e-Learning Centre, UCSC
3
States managed by readyState
property
9
© 2020 e-Learning Centre, UCSC
4
Caching and AJAX
9
© 2020 e-Learning Centre, UCSC
5
AJAX and Cached pages
• Web browsers are capable of caching the response
returned by a specific URL.
• It is important to reduce the amount of data the
browser must download from the server each time.
• Indirectly it cases minimizing the time to load a
web page.
9
© 2020 e-Learning Centre, UCSC
6
Is it problematic caching?
• When caching is applied to HTTP requests, sent by
the XMLHttpRequest object, there is an issue.
• Assume, you use the same URL to retrieve dynamic
data.
• What causes the error??
• Instead of dynamic data to be received, always the
cached data will be given
• Simply, the cached response will be used as the
valid response for the URL .
9
© 2020 e-Learning Centre, UCSC
7
How to solve cache issue with
AJAX
• Solution is to create a unique URL for each HTTP
request.
• This can be done by adding a large random number
as a GET variable/value pair.
9
© 2020 e-Learning Centre, UCSC
8
3.4 Client-side Validation with
3.4 Client-side Validation with JavaScript
JavaScript
IT3406 – Web Application Development II
1
© 2020 e-Learning Centre, UCSC 0
JavaScript validations with a login
form example
• Create a login form with the fields username and
password as shown here.
1
© 2020 e-Learning Centre, UCSC 0
JavaScript validations with a login
form example
• HTML code to create the login form
1
© 2020 e-Learning Centre, UCSC 0
JavaScript validations with a login
form example
• Onsubmit() function calls the JavaScript validation
upon clicking the submit button of the form
1
© 2020 e-Learning Centre, UCSC 0
Validate username field
• Within the script tag write the following code to
validate the username field of the form.
1
© 2020 e-Learning Centre, UCSC 0
Validate username field
• The validateUsername function allows only the
characters a-z, A-Z, 0-9, _ and – as the input for the
username field.
• Further it ensures that usernames are at least five
characters long.
• If it is empty, it returns an error.
• Next, if the username entered is nor empty, but
shorter than five characters, it returns an error
message.
1
© 2020 e-Learning Centre, UCSC 0
Validate username field
• By passing regular expression to test function, it
matches any character that is not one of those
allowed in the regular expression.
• The defined regular expression will be matched
against the field value.
• If any character which is outside the definition of
the regular expression, the function returns true.
• Then the validateUser function returns an error
message.
1
© 2020 e-Learning Centre, UCSC 0
Validate password field
• Within the script tag write the following code to
validate the password field of the form.
• See the defined rules using regular expressions to
check the format of the input field .
1
© 2020 e-Learning Centre, UCSC 0
Validate password field
• First the function checks whether field is empty
• if it is empty, it returns an error
• Next, if the password entered is shorter than six characters, it
returns an error message
• Here the expression specifies three requirements for a
good password
• a lowercase, uppercase, and numerical character
• The test function is called three times, once for each of
these cases
• In case of an absence of any defined criteria, test
method returns false
• Otherwise, the empty string is returned.
1
© 2020 e-Learning Centre, UCSC 0
Putting all JavaScript in a separate
file
• It is good to separate the JS content from the HTML
code
• It makes the maintenance easier than having everything
together
• Link the external JS file into the code using script
tag
External JS File Name
<script src="validate_functions.js"></script>
1
© 2020 e-Learning Centre, UCSC 0
Regular Expressions
• Regular expressions are more important to define
the validation rules.
• Pattern matching is the main principal behind
regular expressions.
• Regular expression metacharacters are the key to
define rules for pattern matching in a more
simplified way.
1
© 2020 e-Learning Centre, UCSC 1
Regular expression metacharacters
1
© 2020 e-Learning Centre, UCSC 1
Regular expression metacharacters
1
© 2020 e-Learning Centre, UCSC 1
Regular expression metacharacters
1
© 2020 e-Learning Centre, UCSC 1
Activity
• Implement the following regular expressions and
see how it validates the pattern.
1
© 2020 e-Learning Centre, UCSC 1
Using regular expressions in JS
• JS uses regular expressions in two methods
frequently.
• test method (tells whether the argument matches the
regular expression)
• replace method (takes the second parameter for the
string to replace the text that matches)
• you have already seen) and replace. Whereas test
just, replace takes a second parameter: the string
to.
1
© 2020 e-Learning Centre, UCSC 1
Examples: test() and replace()
test()
document.write(/cats/i.test("Cats are funny. I like cats."))
• If the word cats appear in the string, it returns true.
replace()
document.write("Cats are friendly. I like cats.".replace(/cats/gi,"dogs"))
• Above statement replaces both occurrences of the word cats
with the word dogs.
Note:
• (/g) defines the search as global to find all occurrences.
• (/i) defines to be case-insensitive.
1
© 2020 e-Learning Centre, UCSC 1
3.5 : MVC Architecture and
Tradeoffs
1
© 2020 e-Learning Centre, UCSC 1
Lesson Outline
• MVC Architecture
• Model
• View
• Controller
• Communication among components in MVC
• Alternative Approaches to OOP Web
Development
• MVP method
• MVVM method
1
© 2020 e-Learning Centre, UCSC 1
MVC Architecture
1
© 2020 e-Learning Centre, UCSC 1
MVC Architecture
• MVC stands for model–view–controller.
• MVC method splits object oriented program code
into multiple parts.
• It makes it easier to code and implement the web
site using Object Oriented Programming (OOP).
• Separating the user view and data processing.
components help developers to efficiently code and
easily maintain the code at a later stage
1
© 2020 e-Learning Centre, UCSC 2
MVC Architecture
• The model: One or more classes that interact with
the application data.
• This helps in implementing the business logic to process
data, store and manipulate.
• The view: A class that displays the application data
in the graphical environment.
• The controller: Works as an intermediate for view
and model.
• Listens for user input and passes the input to the
appropriate model class methods for processing.
1
© 2020 e-Learning Centre, UCSC 2
MVC Architecture Component
Interaction Diagram
1
© 2020 e-Learning Centre, UCSC 2
The Model
• The model component contains majority of the
server-side coding (PHP).
• It provides a common interface between the
application and any data.
• The code for model resides between the
application and the database tables.
• Works with data storing, retrieving and
manipulating as required.
1
© 2020 e-Learning Centre, UCSC 2
The Model
• Most MVC model implementations use a technique
called object-relational mapping (ORM) to provide
this interface.
• The ORM class is responsible for handling the
methods for all interaction with the underlying
table (CRUD Operations):
• Creating new data records
• Reading existing data records
• Updating existing data records
• Deleting existing data records
1
© 2020 e-Learning Centre, UCSC 2
The View
• The view component is responsible for all the
output from the application.
• It takes the raw data provided by the model
component and formats it in a way that’s visually
pleasing to the application user.
• For our web applications, the view component is
where all the HTML and CSS code resides.
• Helps to create applications that support both
desktop and mobile environments with less effort.
1
© 2020 e-Learning Centre, UCSC 2
Views depending on the screen
size
1
© 2020 e-Learning Centre, UCSC 2
Views depending on the screen
size
• MVC architecture provides easy way of creating
applications that support multiple devices.
• All the other processes same except the view
generation.
• For example;
• Devices on the diagram submit the same HTTP request
to the controller, which forwards both requests to the
model.
• The model sends the same responses to the view, but
the view processes the responses differently (see
previous slide diagram).
1
© 2020 e-Learning Centre, UCSC 2
The Controller
• The controller accepts requests from the
application user and sends them to the
components required to satisfy the request.
• The controller uses routing to determine which
model class method to run based.
• on the client browser’s request. Routing maps the
specific HTTP GET or POST.
• request received from a client browser to a specific
model class method.
1
© 2020 e-Learning Centre, UCSC 2
The controller
• MVC controllers utilize the rewrite rules feature of
the webservers .
• Through rewrite rules, the url turns in to clean to
help clean up the format of the request URL.
Rewrite rules allow you to.
• customize the format of the URL to pass
information in a cleaner-looking format.
• than what the standard GET method uses.
1
© 2020 e-Learning Centre, UCSC 2
Communication sequence in MVC
1. The controller receives the request from users
2. The request will be passed to the appropriate
class method implemented in the model
3. The model class method performs the
appropriate action related to data
4. The model class method passes any resulting
data or status to the view
5. The view sends a response back to the website
with the data
1
© 2020 e-Learning Centre, UCSC 3
What issues exist in MVC
architecture
• The controller handles client requests but not
responsible for returning the responses.
1
© 2020 e-Learning Centre, UCSC 3
Other Architecture Models
1
© 2020 e-Learning Centre, UCSC 3
Model-View-Presenter (MVP)
model
• The model–view–presenter (MVP) method is
another popular method of creating object-
oriented web applications.
• In the MVP method, the view handles both the
request and response parts of the process, taking
on the MVC controller’s function of communicating
with the client.
• This eliminates the communication issues identified
in MVC method.
1
© 2020 e-Learning Centre, UCSC 3
MVP diagram
1
© 2020 e-Learning Centre, UCSC 3
MVP method
• The presenter acts as the middleman similar to
MVC architecture.
• It lies in between the model and the view.
• The client requests and calls the appropriate model
class methods.
• The result after processing the request, the
response is sent to presenter.
• Presenter passes the response to the view.
1
© 2020 e-Learning Centre, UCSC 3
Model-View-View Model (MVVM)
method
• Similar to the MVP method viewmodel acts as a
middleman between the view and the model .
• In presenter module it manipulates data in the
MVP method.
• MVVM method the viewmodel does not
manipulate the data.
• Viewmodel just provides an interface between the
view and the model.
1
© 2020 e-Learning Centre, UCSC 3
MVVM method diagram
1
© 2020 e-Learning Centre, UCSC 3
MVVM method
• The viewmodel creates an abstract layer between
the view and the model.
• This abstract layer allows the programmers working
on the view code.
• The mechanism of abstracting helps programmers
to work on separate parts without worrying the
way data are being processed in the underlying
layers.
• Code bases become easily manageable and
maintainable.
1
© 2020 e-Learning Centre, UCSC 3
End
139
4 : Introduction to Web Application Security
4
Storing Web Application Data
1
© 2020 e-Learning Centre, UCSC
1
How cookie works ?
1
© 2020 e-Learning Centre, UCSC
2
How Cookie Works?
1
© 2020 e-Learning Centre, UCSC
3
How Cookie Works? (Cont…)
1
© 2020 e-Learning Centre, UCSC
4
Cookie Attributes
Attribute Description
Domain=site Specifies the domain the cookie applies to. If omitted
the server is the default location.
Expires=datetime Specifies the expiration date for the cookie as an HTTP
timestamp value.
HttpOnly Specifies that the cookie can only be retrieved in an
HTTP session.
Max-Age=number Specifies the expiration time for the cookie in seconds
Path=path Indicates the path in the URL that must exist in the
requested resource.
SameSite=setting Specifies if the cookie can only be accessed from the
same site that set it. Values are Strict or Lax.
Secure Specifies that the cookie can only be sent in an HTTPS
secure session
1
© 2020 e-Learning Centre, UCSC
5
Setting Cookies - setcookie()
1
© 2020 e-Learning Centre, UCSC
7
Modifying and Deleting Cookies
1
© 2020 e-Learning Centre, UCSC
8
Activity 01
1
© 2020 e-Learning Centre, UCSC
9
4.1. Secure Web Applications
4.1.2. HTTP Authentication - Storing Usernames and
Passwords
20
Authentication
2
© 2020 e-Learning Centre, UCSC
1
Identity confirming factors
2
© 2020 e-Learning Centre, UCSC
2
Two-Factor and Three-Factor Authentication
2
© 2020 e-Learning Centre, UCSC
3
Examples of Multi Factor Authentication
2
© 2020 e-Learning Centre, UCSC
4
Web Application Authentication
2
© 2020 e-Learning Centre, UCSC
5
Password-Based Authentication System
2
© 2020 e-Learning Centre, UCSC
6
Built-In HTTP Authentication
Web Application Security, A Beginner's GuideMcGraw-Hill Education;by Bryan Sullivan and Vincent Liu, 1st Edition (2011)
2
© 2020 e-Learning Centre, UCSC
7
Basic Access Authentication
2
© 2020 e-Learning Centre, UCSC
8
Basic Access Authentication
2
© 2020 e-Learning Centre, UCSC
9
Basic Access Authentication - Insecure
1. Insecure Transmission
• Since the data are encoded not encrypted, attacker can decode them since
it lack the security provided by encryption.
• To secure credentials in transit, it must be submitted over SSL connection
or encrypted medium
2. Repeated Exposure
• Credentials must be submitted with the every single request for a
protected resources.
• Credentials are exposed over and over with each request to the web server
3. Insecure Storage
• Since credentials need to submit with each request, the browser caches the
authentication credentials.
• Since no session is created, we cant invalidate a session with the web
server.
• The only way to clear the stored credentials is to close the tab and clear
the history.
3
© 2020 e-Learning Centre, UCSC
0
Digest Access Authentication
3
© 2020 e-Learning Centre, UCSC
1
Digest Access Authentication
3
© 2020 e-Learning Centre, UCSC
2
Activity 02
3
© 2020 e-Learning Centre, UCSC
3
Single Sign-on Authentication (SSO)
3
© 2020 e-Learning Centre, UCSC
4
Single Sign-on Authentication (SSO)
3
© 2020 e-Learning Centre, UCSC
5
Custom Developed Authentication Mechanisms
3
© 2020 e-Learning Centre, UCSC
6
Web Authentication Process
Web Application Security, A Beginner's GuideMcGraw-Hill Education;by Bryan Sullivan and Vincent Liu, 1st Edition (2011)
3
© 2020 e-Learning Centre, UCSC
7
Web Authentication Process (Cont…)
3
© 2020 e-Learning Centre, UCSC
8
Web Authentication Process (Cont…)
5. The web application logic queries the back-end data stores
to determine whether or not the password entered is
associated with the username entered.
a. If the matching unsuccessful web application sends an error message
along with login page
b. If successfully matched, web application will established a session with
a user by generating a session ID value and returning it to the user by
setting a cookie in the HTTP response.
6. When the browser receives and parse the HTTP response, it
will observe the Set-Cookie directive in the HTTP header and
store the value of the session ID
a. Since session ID value was set in a cookie, browser will submit the
session ID alongside all requests made to the web application. This is
a form of persistent authentication since user don’t need to enter
credentials again and again to authenticate every request.
b. When web application parse a request from this browser see the
session ID values and know that an existing session has already been
established and authorized each request within the application logic
3
© 2020 e-Learning Centre, UCSC
9
Activity 03
4
© 2020 e-Learning Centre, UCSC
0
Validating Credentials
• There are different ways to determine whether the supplied
password associate with the supplied username.
• There are basically two variable involved in validating credentials,
1. Location of the comparison logic
a. Within application
b. Database
2. How the password is stored
a. Plain text – Compare plain text
b. Hashed – Compare the hashed values
• Taking the cross-product of these variables give 4 approaches to
validate the credentials
1. Comparison logic in the application with plaintext passwords
2. Comparison logic in the database with plaintext passwords
3. Comparison logic in the application with hashed passwords
4. Comparison logic in the database with hashed passwords
4
© 2020 e-Learning Centre, UCSC
1
Attacks Against Passwords
• Since password is pervasive as an authentication factor in web
applications, they are very popular target of attackers.
• All attacks against password try to determine the plain text
value of password.
• Basically there are two types of attempts to determine the
plain text,
• Against live system (online)
• Against the hashed or encrypted password value (offline)
4
© 2020 e-Learning Centre, UCSC
2
Attacks Against Passwords - Online
• Online attacks are slow
Web Application Security, A Beginner's GuideMcGraw-Hill Education;by Bryan Sullivan and Vincent Liu, 1st Edition (2011)
4
© 2020 e-Learning Centre, UCSC
3
Attacks Against Passwords - Offline
• Offline attacks are much faster
Web Application Security, A Beginner's GuideMcGraw-Hill Education;by Bryan Sullivan and Vincent Liu, 1st Edition (2011)
4
© 2020 e-Learning Centre, UCSC
4
Attacks Against Passwords (Cont…)
Common attack variations include,
• Dictionary attack -
• Try to find the password by entering real words can be found in
dictionaries
• In some cases real world dictionaries or permutated
dictionaries(appending a digit or special character) will be used.
• Brute-force attack (Exhaustive key search) -
• Theoretically, attempting every single possible key
• Practically, place several limitations based on the length, character
set
• This is rarely used and used in offline attacks against hashed
password values
• Precomputed dictionary attack -
• Hashed the dictionaries and store in a disk in advance and used the
hash only to match two password hashes
• Trade time for disk space
• Rubber-hose attack -
• Extracting password from individuals using any sort of physical
coercion
4
© 2020 e-Learning Centre, UCSC
5
Activity 04
4
© 2020 e-Learning Centre, UCSC
6
Password Best Practices
• Improve the size of the key and make key space larger
The number of possible permutations of a set of x characters with
length y is calculated with x^y.
26^12 = 9.54*1016
• Regularly change the password
Best practice is to rotate password at least every 90 days.
• Use unique passwords when changing the password
When rotating the password we shouldn’t use the a password which
has been used recently.
• Allow accounts to be disabled when they are not using it
• Properly store passwords
Store only if it is absolutely necessary without using plain text and
encryption. Use strong hashing.
• Use random salt values with each password
In addition to hashing use random salt value to increase security
4
© 2020 e-Learning Centre, UCSC
7
Secure Authentication Best Practices
• Secure the transmission by using an encrypted channel
• To counter online attacks we can lock accounts after certain
number if failed logins
• Using CAPTCHAs which can only be answered by a human to
discourage online brute force attacks
• Allow accounts to be disabled when user is not using the
system for a while
• Don’t release applications to production with default accounts
such as ‘Admin’, ‘Administrator’, ‘Guest’
• Don’t hard code credentials within the web application
4
© 2020 e-Learning Centre, UCSC
8
4.1. Secure Web Applications
4.1.3. Using Sessions – Starting and Ending Sessions,
Session Security and Timeout
49
Session
5
© 2020 e-Learning Centre, UCSC
0
Session
5
© 2020 e-Learning Centre, UCSC
1
Starting a Session
5
© 2020 e-Learning Centre, UCSC
2
Storing and Retrieving Session Data
5
© 2020 e-Learning Centre, UCSC
3
Removing Session Data
5
© 2020 e-Learning Centre, UCSC
4
Activity 05
5
© 2020 e-Learning Centre, UCSC
5
Summary
• Types of cookies
• Attributes of cookies
Cookies • Setting cookies
• Reading cookies
• Modifying and deleting cookies
• Authentication fundamentals
• Web application authentication
Authentication • Attacks against password
• Password best practices
• Web authentication best practices
• Starting a session
Session • Storing
© 2020 e-Learning and retrieving data
Centre, UCSC
• Removing data
5
© 2020 e-Learning Centre, UCSC
6
Overview – Chapter 4.2
5
© 2020 e-Learning Centre, UCSC
7
Activity 06
5
© 2020 e-Learning Centre, UCSC
8
4.2. Common Types of Vulnerabilities
4.2.1. Injection
59
Injection
6
© 2020 e-Learning Centre, UCSC
0
Injection
6
© 2020 e-Learning Centre, UCSC
1
Injection - Security Weakness
6
© 2020 e-Learning Centre, UCSC
2
Injection - Impacts
6
© 2020 e-Learning Centre, UCSC
3
Injection – Vulnerabilities
6
© 2020 e-Learning Centre, UCSC
5
Injection – Examples
6
© 2020 e-Learning Centre, UCSC
7
4.2. Common Types of Vulnerabilities
4.2.2. Cross-site Scripting
68
Cross-site Scripting (XSS)
6
© 2020 e-Learning Centre, UCSC
9
Cross-site Scripting (XSS)
7
© 2020 e-Learning Centre, UCSC
0
Cross-site Scripting - Threat Agents
7
© 2020 e-Learning Centre, UCSC
1
Cross-site Scripting - Security Weakness
7
© 2020 e-Learning Centre, UCSC
2
Cross-site Scripting - Impacts
7
© 2020 e-Learning Centre, UCSC
3
Cross-site Scripting - Vulnerabilities
7
© 2020 e-Learning Centre, UCSC
4
Cross-site Scripting – How to Prevent
7
© 2020 e-Learning Centre, UCSC
5
Cross-site Scripting – Examples
7
© 2020 e-Learning Centre, UCSC
6
4.2. Common Types of Vulnerabilities
4.2.3. Broken Authentication and Session Management
77
Broken Authentication
7
© 2020 e-Learning Centre, UCSC
8
Broken Authentication
7
© 2020 e-Learning Centre, UCSC
9
Broken Authentication - Threat Agents
8
© 2020 e-Learning Centre, UCSC
0
Broken Authentication - Security Weakness
8
© 2020 e-Learning Centre, UCSC
1
Broken Authentication - Impacts
8
© 2020 e-Learning Centre, UCSC
2
Broken Authentication - Vulnerabilities
8
© 2020 e-Learning Centre, UCSC
4
Broken Authentication – Examples
86
Security Misconfiguration
8
© 2020 e-Learning Centre, UCSC
7
Security Misconfiguration - Threat Agents
8
© 2020 e-Learning Centre, UCSC
8
Security Misconfiguration - Security Weakness
8
© 2020 e-Learning Centre, UCSC
9
Security Misconfiguration
9
© 2020 e-Learning Centre, UCSC
0
Security Misconfiguration - Impacts
9
© 2020 e-Learning Centre, UCSC
1
Security Misconfiguration - Vulnerabilities
9
© 2020 e-Learning Centre, UCSC
3
Security Misconfiguration – Examples
95
Insecure Cryptographic Storage
9
© 2020 e-Learning Centre, UCSC
6
Insecure Cryptographic Storage - Threat Agents
9
© 2020 e-Learning Centre, UCSC
7
Insecure Cryptographic Storage - Security Weakness
9
© 2020 e-Learning Centre, UCSC
8
Insecure Cryptographic Storage - Impacts
9
© 2020 e-Learning Centre, UCSC
9
Insecure Cryptographic Storage - Vulnerabilities
1
© 2020 e-Learning Centre, UCSC 0
Insecure Cryptographic Storage – How to Prevent
1
© 2020 e-Learning Centre, UCSC 0
4.2. Common Types of Vulnerabilities
4.2.6. Failure to Restrict URL Access
104
Failure to Restrict URL Access
1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access - Threat Agents
1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access - Security Weakness
1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access - Impacts
1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access - Vulnerabilities
1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access – How to Prevent
1
© 2020 e-Learning Centre, UCSC 1
Failure to Restrict URL Access – Examples
112
Unvalidated Redirects and Forwards
1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects
1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Forwards
1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects and Forwards - Threat Agents
1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects and Forwards - Security Weakness
1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects and Forwards - Impacts
1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects and Forwards - Vulnerabilities
1
© 2020 e-Learning Centre, UCSC 2
Unvalidated Redirects and Forwards – Examples
1
© 2020 e-Learning Centre, UCSC 2
4.2. Common Types of Vulnerabilities
Vulnerabilities Included in OWASP Top Ten List
122
OWASP
1
© 2020 e-Learning Centre, UCSC 2
OWASP Top Ten
https://owasp.org/www-project-top-ten/
1
© 2020 e-Learning Centre, UCSC 2
OWASP Comparison
https://www.incibe-cert.es/en/blog/owasp-publishes-top-10-2017-web-application-security-risks
1
© 2020 e-Learning Centre, UCSC 2
Activity 09
1
© 2020 e-Learning Centre, UCSC 2
Summary
• Injection
• Cross-Site Scripting (XSS)
• Broken Authentication and Session
Common types of Management
vulnerabilities • Security Misconfiguration
• Insecure Cryptographic Storage
• Failure to Restrict URL Access
• Unvalidated Redirects and Forwards
1
© 2020 e-Learning Centre, UCSC 2
4.3. Differentiate Client and Server Security
4.3.1. Securing Server and Client Machines
129
Securing Server and Client Machines
1
© 2020 e-Learning Centre, UCSC 3
4.3. Differentiate Client and Server Security
4.3.2. Securing Client Application and Apache Web Server
132
Securing Client Application and Apache Web Server
1
© 2020 e-Learning Centre, UCSC 3
SuExec
1
© 2020 e-Learning Centre, UCSC 3
4.3. Differentiate Client and Server Security
4.3.3. Configure PHP Securely
136
Configure PHP Securely
• register_globals = off :
If this parameter is enabled, all environment, GET, POST, cookie,
and server variables are registered as globals, making them
easily available to attackers. Unless you have no other options
but to enable it, you should leave register_globals off.
• display_errors = off :
Prevents PHP errors and warnings from being displayed to the
user. Not only do PHP warnings make your site look
unprofessional, but they also often reveal sensitive information,
such as pathnames and SQL queries.
• log_errors = on :
When this parameter is enabled, all warnings and errors are
written to a log file in which you can examine those warnings
and errors later.
• error_log = filename :
Specifies the name of the log file to which PHP should write
errors and warnings.
1
© 2020 e-Learning Centre, UCSC 3
Activity 11
1
© 2020 e-Learning Centre, UCSC 3
4.3. Differentiate Client and Server Security
4.3.4. Handling Errors Safely
140
Understanding the Danger
• Attackers can inject SQL queries to forms and assume that they
will execute in the database.
Eg 01: John; drop%20table%20users.
If the application is setup to enter user name into database
INSERT INTO users VALUES (John; drop table users);
If the database is loosely configured, it will insert ‘Dasun’ into the user
table and drop the table named users.
Eg 02: John’ OR ‘foo’ = ‘foo’ --
If this text enter to username field,
$sql = “SELECT * FROM User WHERE username = ‘John’ OR ‘foo’ =
‘foo’ -- ‘ AND password = ‘$_POST[password]’”;
This query allows the user to log in without a valid username or
password.
In the first phrase in the WHERE clause, the foo = foo is true. Then, the
--makes the rest of the query into a comment, effectively invisible in
the query
1
© 2020 e-Learning Centre, UCSC 4
Handling Errors Safely
Attackers enter things into your form for nefarious purposes, in
order to handle those errors safely,
• Test for unexpected inputs
• Can make assumptions about the data you expect the user to enter and
pass them through regular expressions using PHP preg_match function
to make sure it does not contain any nonalphabetical characters, other
than a space, an apostrophe or a hyphen.
• Hijacking and cross site scripting can be done by inject markup into web
application, which can be prevent using htmlentities function
• Handling the unexpected
• Simplest way to handle is to stop the application completely, but it can
cause confusion and frustration for legitimate users who accidently
mistyped their information
• Better to redirect user to the input screen and ask them to try again and
can be make it more user-friendly by letting users know which fields
caused problems.
• Check all form data
• Since drop downs and radio buttons data also can be manipulated it is
better to validate what you expect to receive against what you actually
received for all form data. 1
© 2020 e-Learning Centre, UCSC 4
Activity 12
1
© 2020 e-Learning Centre, UCSC 4
4.3. Differentiate Client and Server Security
4.3.5. Sanitizing Variables
144
Sanitizing Variables
Without telling the users to go back and try again when they
enter invalid data, we can use some techniques to ensure the
bad data does not break the application
• Converting HTML special characters
• Uploading files without compromising the filesystem
http://xkcd.com/327/
1
© 2020 e-Learning Centre, UCSC 4
Converting HTML Special Characters
1
© 2020 e-Learning Centre, UCSC 4
Uploading Files Without Compromising the Filesystem
(Cont…)
We can mitigate the danger by,
• Avoiding DoS attacks on the filesystem
• By uploading large files can effectively bring the server down by
preventing it from writing temporary files or virtual memory swap
files.
• Can limit file size in php.ini, but it wont prevent a scripted attack
that tries to upload hundreds of 2MB files every second.
• While reducing the file size, create separate filesystem for uploaded
file which will protect the rest of the server by locking any mischief.
• Validating files
• Verify the filename extension
• Test for the basic file type you’re expecting
• Run the file through an antivirus utility such as F-Prot
1
© 2020 e-Learning Centre, UCSC 4
Uploading Files Without Compromising the Filesystem
(Cont…)
• Using FTP functions to ensure safe file uploads
• Using PHP’s built-in fopen() function, ripe for exploitation by
malicious users who can use it to upload files from remote servers
onto your web server.
• We can prevent this by disable two settings in php.in: register_globals
and url_fopen.
• When using FTP functions. First, you establish a connection, then you
upload the files you need, and finally, you close the connection.
1
© 2020 e-Learning Centre, UCSC 4
Summary
Securing client
• SuExec
application and • Mod_security
apache web server
Configure PHP
• Security related options in php.ini
securely
• https://owasp.org/www-project-top-ten/Description
• PHP, MySQL, & JavaScript All-in-One For Dummies Richard
Blum, 2017 (Online source : https://www.pdfdrive.com/php-
mysql-javascript-all-in-one-for-dummies-e90592496.html)
• PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies ,
John Wiley & Sons, Inc. 2013
• Web Application Security, A Beginner's GuideMcGraw-Hill
Education;by Bryan Sullivan and Vincent Liu, 1st Edition
(2011)
1
© 2020 e-Learning Centre, UCSC 5