0% found this document useful (0 votes)
2K views390 pages

CS521 Slides Week (7 To16) Made by MAH JABEEN

Uploaded by

Arts Shop
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views390 pages

CS521 Slides Week (7 To16) Made by MAH JABEEN

Uploaded by

Arts Shop
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 390

WEEK 7

TOPIC 55 TO 63
Web Systems and Technologies

• Modifying DOM Elements


• Creating DOM elements
• Event Handling
• Capturing and Bubbling
• Event Types
• Form Validation; Client Side Input Validation
• Introduction to jQuery
• Query Selectors
• jQuery Manipulators
EVENT TYPES

• Mouse events
• Keyboard events
• Touch events
• Form events
• Textfield events
WEEK 8
TOPIC 64 TO 72
Only audio/video lectures
Web Systems and Technologies

• Query Manipulators - Example


• Events in Query
• DOM Manipulation using jQuery
• Animations using jQuery
• Introduction to Ajax
• Asynchronous File Transmission
• Introduction to server side development, Comparison of server side technologies
• Installation of Apache webserver, PHP and MySQL for Local Development
• Introduction to PHP
WEEK 9
TOPIC 73 TO 81
Web Systems and Technologies

• 73 -Introduction to PHP (String Concatenation)


• 74 - Program Control - Conditional Program Statements
• 75 Program Control - Loops
• 76 Functions in PHP (1)
• 77 Functions in PHP(2)
• 78 Arrays in PHP
• 79 Sorting Arrays
• 80 Arrays - Super Global
• 81 $_GET and $_POST Arrays
WEEK 10
TOPIC 82 TO 90
Web Systems and Technologies

• 82 $_GET and $_POST arrays - Example


• 83 $_SERVER Array
• 84 $_FILES Array
• 85 Reading and Writing Files
• 86 Classes and Objects in PHP; Object Properties
• 87 Constructor; Methods
• 88 Visibility
• 89 Static members; Constants
• 90 Databases and Web Development
$_GET and $ POST
Superglobal Arrays -
Example
$_SERVER Array
Server Information Keys
S SERVER ( ”REQUEST
I1ETH0D ” ) $ SERVER | SERVER PROTOCOL ” )

POST / page 1p /

mysite. pom —S SERVER | ”nT7P HOST ' I


S RS|E”HTIP
S SERVF ”REOUEST
RVER( uSEP AG T' II hE ' ] — U
Da
setr e- Ag en
Sunt . 20 la 2012 23 S9 59 GS
Accapt - Encodl ng y T $ SERVER [ ' HTTP ACCEPT E8C0DI xG ' )
S SERvER | ”HTTP ñ0xnECT l0N ' j
Connec t 1 on Ke ep - Al i v e

<htm1 >
HTTP Request Hea der
Request Header Information Keys
• Advanced browser detection, need to get
browscap.ini and configure php.ini
[browscap] to use it

echo $ S5FVER['HTTP USER AGENT');


+br‹:›wser
Diowser($ SERVER['HTTP USER AGENT')
Request Header Informañon Keys

$previousPage =
$ SERVER['HTTP REFERER');
// Check to see referer was
search page
( st r p o s ( S p r e v i ousPage, " s e a r c h . php" )
! = 0)
echo "Ca href='search.php'>Back to
search</a>";

// Rest of HTML output


$_FILES Array
HTML Required for File Uploads

• First, you must ensure that the HTML


form uses the HTTP POST method
• Second, you must add the
enctype="muItipart/form-data" attribute to the
HTML form that is performing the upload
• Finally you must include an input type of file
in your form.
enctype='multipart/form-data'

type= 'file' name=' filRl '

type='submit'>
Handling
< f n r m the File
-
'
'Upload ini PHP
'
oe t hon - ’ pt s t ac t i on -
(cl icn I) < i r Pu I I y pe- ' su bm i I ’ v a \ rl e = "S u Uri I flu e r y “ » ’
< / f a rm>
HTnL <i i '‹ • ' name- ' I '>
npuI

Bi uws ei-
(cl ient)

POST upFi ie php


HTTP
r eques I HTTP POST n u\tipart/form data
C'hecktng far’E’rrom

fore'ach (S FI:LES ‹as $fileKey => $fileArray) (


if (S:fiIbArr‟ay("error") != UPLOAD_ERR OK) i // error
echo "Ermor: " . $fileKey . " has error" .

else .( // no error
ech:o $fileKey . "Uploaded successfully ";

.
File Size Restrictions

• You can limit in multiple ways


• HTML form attributes in inputs
(browser)
• JavaScript (browser)
• PHP validation (server)
Limiting.the Type of’File.Upload
$‟ v‟ a‟ l" i•d E‟x t. =‟a r'r :*a y em j p g T , 0
png *);
SvalidMime: = array("image/jpeg","image/png");
"”
fo.ea•
r '• (•
c h. $”.F
..I..'.
L ”.
ES ”
a.s S”
f"•..•

i leKey => $fileArray }{
$extentJt% - ehd(explode(".", $fileArray{"name"])}; if (in
array($fileArray["type"],$validMime)
&& lh“array($extension, $validExt)) {
echo 'Al:1 is. well. Extension and mime types valid#;
tJoving the Fïle
Reading/Writing Files
Two ways
• There are two basic techniques for
read/writing files in PHP:
Stream access. Just read a small portion
of the file at a time
All-In-Memory access. Read the entire file into
memory (i.e., into a PHP variable). While not
appropriate for large files, it does make
processing of the file extremely easy.
Stream Access
• To those of you familiar with functions like
fopen() , fclose() , and fgets() from the C
programming language, this first technique
will be familiar

• Open fopen()
• Read data fgets()
• Close the file fclose()
In-Memory File Access
• file() Reads the entire file and returns an
array, with each array element
corresponding to one line in the file.
• fiIe_get_contents() Reads the entire file
and returns a string variable.
• fiIe_put_contents() Writes the contents of a
string variable out to a file.
Classes and Objects in
PHP
Defining Classes
lnstantiating Objects
• Use the new keyword

$picasso — new Artist();


Şdali = new Artist();
Properties
• Once you have instances of an object, you can
access and modify the properties
using the object's variable name and an
arrow (->)
$picasso new Artist();
Sdali new Artist();
$picasso—>firstName "Pablo";
$picasso—>lastName "Picasso";

$picasso->birthCity = "Malaga",

Spicasso>birthDate "October 25 1881";


Web Systems and Technologies

TOPIC 87

Classes and Objects in


PHP Constructor &
Methods
Classes and Objects in PHP
Constructor
class Artist {
function __construct($firstName, $lastName, $city, $birth,
$death=null) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->birthCity = $city;
$this->birthDate = $birth;
$this->deathDate = $death;
}
}
Classes and Objects in PHP
Instantiating using Constructors

$picasso = new
Artist(“Pablo”,“Picasso”,“Malaga”,“Oct 25,1881”, “Apr 8,1973”);
$dali = new
Artist(“Salvador”,“Dali”,“Figures”,“May 11 1904”, “Jan 23 1989”);
Classes and Objects in PHP
Methods
• Methods define the tasks each instance of a class can perform and are useful since
they associate behavior with objects

class Artist {
// …
public function outputAsTable() {
//…
}
}

$a->outputAsTable()
Web Systems and Technologies

TOPIC 88

Classes and Objects in


PHP Visibility
Classes and Objects in PHP
Visibility
Web Systems and Technologies

TOPIC 89

Classes and Objects in


PHP Static Members &
Constants
Classes and Objects in PHP
Static Members
• A Static member is a property or method that all
instances of a class share
• Static value is shared across all instances

class Artist {
public static $artistCount = 0;
public static function addArtist() {
self:: $artistCount++;
}
}
Artist::addArtist();
print(Artist::$artistCount);
Classes and Objects in PHP
Class Constants
• Constant Values can be stored more efficiently as
class constants so long as they are not calculated or
updated
Const EARLIEST_DATE =‘January1, 1200’;
• They can be accessed both inside and outside theclass
using self::EARLIEST_DATE in the class and
classReference::EARLIEST_DATE
Web Systems and Technologies

TOPIC 90

Databases and Web


Development
Databases and Web Development
The Role of Databases in Web Development

• HTML pages remain constant


• Using databases with PHP allows to make parts of
HTML dynamic(variable)
Databases and Web Development
Role of
databases in
web
development
Databases and Web Development

How websites
use databases
Databases and Web Development
Database
options
WEEK 11
TOPIC 91 TO 99
SQL,Database,PHP

• 91 SQL - Select, Insert, Update, Delete


• 92 Introduction to MySQL
• 93 phpMyAdmin
• 94 Accessing MySQL in PHP
• 95 Fetching Data
• 96 Performing Transactions
• 97 Example: Database Creation
• 98 Example: Database Insertion
• 99 Example: Database Search
Web Systems and Technologies

Accessing MySQL in PHP


Fetching Data
Accessing MySQL in PHP
Executing the query
$sql = “SELECT * FROM Categories ORDER BY CategoryName”;

// returns a mysqli_result object

$result = mysqli_query($connection, $sql);

OR

$result = $pdo->query($sql);
Accessing MySQL in PHP
Processing the Query Results
$sql = “SELECT * FROM Categories ORDER BY CategoryName”;
// run the query
$result = $pdo->query($sql);
// fetch a record from result set into an associative array
while ($row = $result->fetch()) {
// the keys match the field names from the table
echo $row['ID'] . “ - ” . $row['CategoryName'];
echo “<br/>”;
}
Accessing MySQL in PHP
Processing the Query Results
Accessing MySQL in PHP
Freeing Resources and Closing Connection
// close the connection

mysqli_close($connection);

// closes connection and frees the resources used by the PDO


object

$pdo = null;
Accessing MySQL in PHP
Working with Parameters
$sql = “UPDATE Categories SET CategoryName='Web' WHERE

CategoryName='Business'”;

$count = $pdo->exec($sql);

echo "<p>Updated ” . $count . “ rows</p>”;


Accessing MySQL in PHP
Working with Parameters – Technique 1 ? Placeholders
$sql = “INSERT INTO books (ISBN10, Title, CopyrightYear, ImprintId,
ProductionStatusId, TrimSize, Description) VALUES (?,?,?,?,?,?,?)”;
$statement = $pdo->prepare($sql);
$statement->bindValue(1, $_POST['isbn']);
$statement->bindValue(2, $_POST['title']);
$statement->bindValue(3, $_POST['year']);
$statement->bindValue(4, $_POST['imprint']);
$statement->bindValue(5, $_POST['status']);
$statement->bindValue(6, $_POST['size']);
$statement->bindValue(7, $_POST['desc']);
$statement->execute();
Accessing MySQL in PHP
Working with Parameters – Technique 1 ? Placeholders
with Array
$sql = “INSERT INTO books (ISBN10, Title, CopyrightYear, ImprintId,
ProductionStatusId, TrimSize, Description) VALUES (?,?,?,?,?,?,?)”;
$statement = $pdo->prepare($sql);
$statement->execute
(array($_POST['isbn'],
$_POST['title'], $_POST['year'],
$_POST['imprint'], $_POST['status'],
$_POST['size'],$_POST['desc']);
Accessing MySQL in PHP
Working with Parameters – Technique 2 ? Named Parameters
$sql = “INSERT INTO books (ISBN10, Title, CopyrightYear, ImprintId,
ProductionStatusId, TrimSize, Description) VALUES (:isbn,
:title, :year, :imprint, :status, :size, :desc) ”;
$statement = $pdo->prepare($sql);
$statement->bindValue(':isbn', $_POST['isbn']);
$statement->bindValue(':title', $_POST['title']);
$statement->bindValue(':year', $_POST['year']);
$statement->bindValue(':imprint', $_POST['imprint']);
$statement->bindValue(':status', $_POST['status']);
$statement->bindValue(':size', $_POST['size']);
$statement->bindValue(':desc', $_POST['desc']);
$statement->execute();
Accessing MySQL in PHP
Working with Parameters – Technique 2 ? Named Parameters with Array
$sql = “INSERT INTO books (ISBN10, Title, CopyrightYear, ImprintId,
ProductionStatusId, TrimSize, Description) VALUES (:isbn,
:title, :year, :imprint, :status, :size, :desc) ”;
$statement = $pdo->prepare($sql);
$statement->execute(array(':isbn' => $_POST['isbn'],
':title'=> $_POST['title'],
':year'=> $_POST['year'],
':imprint'=> $_POST['imprint'],
':status'=> $_POST['status'],
':size'=> $_POST['size'],
':desc'=> $_POST['desc']));
Accessing MySQL in PHP
Getting User Input into a Query
Web Systems and Technologies

Accessing MySQL in PHP


Performing Transactions
Accessing MySQL in PHP
Using Transactions
$pdo = new PDO($connString,$user,$pass);
try {
// begin a transaction
$pdo->beginTransaction();
// a set of queries: if one fails, an exception will be thrown
$pdo->query(“INSERT INTO Categories (CategoryName) VALUES („Philosophy')”);
$pdo->query(“INSERT INTO Categories (CategoryName) VALUES ('Art')”);
// if we arrive here, it means that no exception was thrown
$pdo->commit();
} catch (Exception $e) {
// we must rollback the transaction since an error occurred with insert
$pdo->rollback();
}
Topic 97 to 99 are examples
WEEK 12
TOPIC 100 TO 108
Web Systems and Technologies

• 100 Example: Database Update


• 101 Error Handling in PHP; Types of Error
• 102 PHP Error Reporting
• 103 PHP Error and Exception Handling
• 104 Regular Expressions
• 105 Regular Expressions - Examples
• 106 PHP Filters
• 107 Validating User Input
• 108 Where to Perform Validation
Types of Errors
• Expected errors
• Warning errors
• Fatal errors
Types rrors
Notice that this parameter has no value.

Il=0&n. m=l"& '=sm#th&nnm *-%20


Example query string:
This parameter's value is a space character (URL encoded).

returns true

Notice that a missing value for a parameter is


i me I ( $ GET returns true still considered to be 1s6et.

l»ut(% GET( returns true

returns true

Notice that only a missing parameter name


returns
is considered to be not 1 sset.

Notice that a value of zero is considered to be


returns true empty. This may be an issue if zero is a
"legitimate" value in the application.

empty( GET(' returns true

eopt y ( $ GET returns fa1ee

Notice that a value of space is


returns
considered to be not empty.

nn›t›t y ( $ NET ' returns true


The error_reporting Setting

• error_reporting specifies which type of


errors are to be reported
• Can be configured using
ini set(...);
• Or within the php.ini file
The display errors Setting

• The dispIay_error setting specifies


whether error messages should or
should not be displayed in the browser
• ini_set('dispIay_errors','0');
• It can also be set within the php.ini file:
• dispIay_errors = Off
The log_errors Setting

• The Iog_errors setting specifies


whether error messages should or should
not be sent to the server error

• ini_set('Iog_errors','1');
• It can also be set within the php.ini
file:
• log errors = On
Exceptions

• An exception refers to objects that are of


type Exception and which are used in
conjunction with the object- oriented try ...
Catch language construct for dealing with
runtime errors.
Procedural Error Handling
connect(DBHOST, DBUSER,
DBPABS, DBNAME);
connect

// handle the error


Object-Oriented Exception Handling

$connection connect(DBHOST, DBUSER, DBPASS, DBNAME


throwException("error");

catch (Exception

echo Caughc excepcion: $e->getMessage();


On Line $e->getLine();

Stack Trace: print r($e->getTrace()),


Introduction
• A regular expression is a set of special
characters that define a pattern
• Regular expressions are a concise way to
eliminate the conditional logic that would be
necessary to ensure that input data follows a
specific format
• PHP, JavaScript, Java, the .NET environment, and
most other modern languages support regular
expressions (each slightly different)
Regular Expression Syntax
• A literal is just a character you wish to
match in the target
• A metacharacter is a special symbol that
acts as a command to the regular
expression parser
• .[] ()^$| *? {}+
• Regular Expression Patterns can be
combined to form complex expressions


11
Regular Expression Syntax Patterns

• ^qwerty$ If used at the very start and end of


the regular expression, it means that the
entire string (and not just a substring) must
match the rest of the regular expression
contained between the ^ and the $ symbols.
• \t Matches a tab character.
• \n Matches a new-line character.
• . Matches any character other than \n.
Regular Expression Syntax Patterns

• [qwerty] Matches any single character of the


set contained within the brackets.
• [^qwerty] Matches any single character
not contained within the brackets.
• [a-z] Matches any single character
within range of characters.
• \w Matches any word character.
Equivalent to [a-zA-Z0-9].
• \W Matches any nonword character.
Regular Expression Syntax Patterns

• \s Matches any white-space


character.
• \S Matches any nonwhite-space
character.
• \d Matches any digit.
• \D Matches any nondigit.
• * Indicates zero or more matches.
• + Indicates one or more matches.
• ? Indicates zero or one match.
Regular Expression Syntax Patterns
• {n} Indicates exactly n matches.
• {n,} Indicates n or more matches.
• {n, m} Indicates at least n but no more
than m matches.
• | Matches any one of the terms
separated by the | character.
Equivalent to Boolean OR.
• () Groups a subexpression. Grouping can
make a regular expression easier to
understand.
Regular Expressions - Examples
• CNIC
Examples

• Email Addresses

• Mobile numbers in Pakistan


Introduction

• Filters in PHP validate input against


predefined patterns
Validate filters
Sanitize filters
• Use the function
fiIter_var($vaIue, FILTER)
Validate Filters
• Check input against a pre-defined pattern
• Validate email (FILTER_VALIDATE_EMAIL)
$ei ii fillei var('ab:Umarl.r‹i',FILTER VALIDATE EMAIL);
//$email = abcÜmail.com
$omail
filter var('abcW.‹n)m',tIT fER VALIULTE EMAIL);
/ / c x i a i J n « i 1
• Other validate filteres
FILTER_VALIDATE_BOOL, FILTER_VALIDATE_FLOAT, F FILTER R VALIDAT
VALIDATE MAC

• FILTER_VALIDATE_IP
• FILTER VALIDATE URL
• FILTER_VALIDATE_REGEXP
Validate Filters
• Validate against a regular expression (FILTER_VALIDATE_REGEXP)
var('12345-1234567-8', FILTER VALIDATE REGEXP,
array("options" array("regexp > "/‟\\d(5)-&1 d 7!-? d4 ")) ;

e who " Anya l id CN TC" ;

"Valid CNIC $cnic


Validate Filters
• Validate against a regular expression (FILTER VALIDATE REGEXP)
var('1234a-l234o67-8', FILTER VALIDATE REGEXP,
array("options" array("regexp" > "/‟\\d{o)-?\\d(7)-?\\d$/")) ;

echo "Invalid CNIC"; echo "Valid CNIC

$cnic";
Sanitize Filters
• Remove or replace specific characters

• FILTER SANITIZE EMAIL


• FILTER SANITIZE STRING
• FILTER SANITIZE FULL SPECIAL CHARS
Sanitize Filters

• FILTER_SANITIZE_ADD_SLASHES
• FILTER_SANITIZE_ ENCODED
• FILTER_SANITIZE_ NUMBER_FLOAT
• FILTER_SANITIZE_ NUMBER_INT
• FILTER_SANITIZE_ SPECIAL_CHARS
• FILTER_SANITIZE_ URL
Types of Input Validation

• Required information
• Correct data type
• Correct format
• Comparison
• Range check
• Custom
Notifying the user

Form Validation Examples

e n alkipeoie org/wIkł The żttsrry Ni{


Pop-up tool tip (appears
when mouse hovered over
Icon)

Pop-over
How to Reduce Validation Errors Use Input Masks
Bigger Picture

User submits form

If errors, cancel submit


and display error
messages t allow user . .” If no errors,
to LO(t8£\ £•FFQFS validate in JavaScript

If no errors, submit form (i.e.,


make request)

Request
O
TOrmPu
PHP page validates
passed data y

If errors, page sends


1 response with error
messages to allow user
@ If nc erro rs,
cont inu e to
to correct errors

process data (e.g., save to


database, etc.)
Validation at the JavaScript Level

• Client process
• Can reduce server load
• Can be bypassed
Validation at the PHP Level

• Validation on the server side using PHP is


the most important form of validation and
the only one that is absolutely essential
WEEK 13
TOPIC 109 TO 117
Web Systems and Technologies

• 109 State Management on Server Side


• 110 State Management Using Query String
• 111 Cookies
• 112 Cookies - Example
• 113 Serialization
• 114 Session State
• 115 Security Principles
• 116 Security by Design
• 117 Authentication
The Problem of state Management
Desktop vs Web Application
What the Sewer Sees
What the User Wants
Solution

• Query Strings
• Cookies
• Sessions
Remember POST andGET

Artist:

T906

Nationality | Spain

Submit

<form mathod-* G 7 action-’process.php’>

<form method= PO T action-'protess.php’>

POST process . php HTTP 1 1


Date: Sun , 15 Jan 2017 23 : 59 : 59 GRI
Ho 9I ' W\fn¥ . OU9 1 t6 . CON
HTTP
Ueer -Agent 8oz 111 a 4. 0 header
Content - Length ! 4
Content -Type : appl 1 cat1 on/ x - - form - ur1 encoded

Query string

Slides by Connolly & HDaF, "Fundamentals of Web Development" - 2’* Ed. Pearson Ed. (3018)
Dynamic vs S atic URLs
• Dynamic URLs (i.e., query strings)
• A pretty essential part of web application
development
• Static URLs
• The appearance of search terms within the
URL does seem to improve its relative pösition.
• Another benefit to static URLs is that
users tend to prefer them.
• Can use URL rewriting to make static URLs
be dynamic
URL Rewriting in Apache
Cookies
How Do Cookies Work?
User makes first request to
page in domain sooss 1I a
User makes another request . com .
to page in domain somes1 t e
. cam,
GET SomePagu . \›hp http/ 1.1 gO9t '
WWW.BOITI S1ta . com
Browser reads cookie
values from text flle for
each subsequent request
for Browser
somes i te . cool

Browser
saves cookie
values in text file and
associates them with
domain somesl te . com . HTTP response contains
cookles In header.
HTTP 1. 1 200 0K
Date: Sun , 15 Jan 2017 23 : 59 : 50 GST Server for somes1
te . com
retrieves these cookie
Set -CODk a : r ame=va values from request
Set - Cock a : name2=va I ue2 E•r› res=Sun 22 Jan 2017 ... header and uses them to
Content -Type: taxt / html customize the response.

Cookie values travel in every subsequent HCP request for that


domain.
GET Anu t hc›rP 1q gi ¢ ht tp/ 1.1
f\EliIlO2=va’I ue2

5IirIes by CDnnolly & I-Ioar, "Fundamentals oT Web Development" - 2'* Ed. Pearson Ed. (7018)
Persistent Cookie Best Practices
• Use cookies for improving user
experience
• User preferences
• User behavior
• The website functionality should not
depend upon cookies
• If using cookies for login information, back it
up with a token on each login, saved on the
server as well
Setting a Cookie

<?php
// add 1 day to the current time
expiry time
$expiryiime time()+60*60*24;
create a persistent cookie
$name "Username";
$value = "Ricardo";
setcookie($name, $value, $expiryTime);
?>
Reading a Cookies

<?php
If (!isset($ COOKIE['Username'] valid cookie found

else
echo ”The username retrieved from the
cookie is:".$ COOKIE['Username' ;

}
?>
Serialization
Introduction

• Serialization converts an object into binary form


• Used for storage and transmission
• Unserialization converts the serialized data back into an object
• Can be used to manage states
• Serialize data at the end of the request
• Unserialize at the start of the next request
Example of Serialization

- name: Chicago
- 1a e t h ar\6 : PM C e8 eO - croat edDate : 1B67
- b1 t EDBt a: 0c t obar 25, 1681 - e1 za : a r ray ( 15 . 2)
- b1 t hC1 t y : ha1 aga - ma1ght ' 1g2 ton a
- da8t hDa t e: Apr11 8, 1B73
- wor k 8 : Ar r ay ( <Art s )

• cT-oatodDate : 1837
- e1ze ' array (7. 6 , 3.5)

C: 8 ; "Ar t \ et " : 764 : ( a: 7! ( a! 8: "ee r11a et ” ; a: \ 2 : ”Oct 25,


188 j " ; e : 5 : "IIr sI Nene" i 8 : "Pab1o" ; e : 4 : "1 g s t Hame" i e: 7 : "P1caa so" ; e: 5
' "b1 r th0et e" ; s ! 12 ! "Oct 2 5. 188 " : s ! 6 : "dest hDot a" ; s : 1 \ : "up1 8,
1873" : a ! 5 : "bJr t hC1 t y ” ; s: 6 : “11al aga" ; e: 5 : "work a" , a ! 3: ( T: 0 ; C: 8 : "Pa1n t
ng" : 134 : {e : 2; (s ; 4 ; "s1ze" ; a : 2: ( 1 : 0 ; d: 7, 74UJ9t›0900J96696 ; 1' 1 ; d : 3. 5 ;
) e: 7 : "ar t Det a " : e' 54 : "a: 2 : (a ! 4 : "date" , e ! 4 ! '*18 57" ' e: 4 ! "nam8" i • : s: “ 8
} " ) }I 'S \ pI t 86 1ght' " 162
ton s " ; a ! \ 2 ! "pa1nt JngData " ; s ! 12 ñ ! "e ! 2 : ( a : 4 ! "s1 ze" ; a : 1 : ( 1 ! 0 ; d: 15. 116
899809986998 : ) s : 7 ' "ar t but a “ ' e : 53 : "a ' 2 : ( a ' 4. “d ate’ : s ' 4 : ’ 1867" , s : 4. "

name™ ; e : 7 : "Ch cago" ; ) " ; ) " : ) ) 1 : 2 ; C: 5 1 75 rted1


't‹1 1' 12 t \ gD 4 : "a1ze" , e ! 2 : ( \ : 0
4,8 } x : 7 : "er t0et e" ; x : 50 : "a: 2: { s: 4 : "da t e" ; a: 4 : " 1988" ; s: 4
'nama " ; s: 4 : "test " : } ” ; ) " ; ) } ) ) )

'Virtue fry fionnnlly 1 I-lull, "f un‹Jan enFals of Web development" 2•* Ed. Pearson Ed. (2018)
Serialization in PHP
Example
class Artist implements Seria izable
public function serialize()
serialize(
array("earliest" >self:: ea ie tDate,
"first" > $this->firstName,
"last"
> $this lastName,
"bdate"
> $this->birthDate,
$this—>deathDate,
"bcity" > $this->birthCity,
"wordr" > $thi ->artworks
class Artist implements Se ializab e

public function unserialize($data) mata


unserialize($data),
self::$earliestDate - $data['ea iest'
$ his—>firstName ;
$data['first'
$this- lastName $data ' a t' ,
$this->birthDate $data['State'];
$this->deathDate $data 'dda e' ;
$this—>birth‹?ity — $data['bcity'],
S th i s —?•a r€ wo r ks
— Sda Fa [ ' wo rks ' ] ;

serialization
How Does Session state work?

SlitTes by Com›ully & I-luar, "Fundamentals of Web Development" - 7 * Ed. Pearson Ed, (sofa)
How does it all work

Slides by Connolly & Hoar,"Fundamentals of Web Development”-2n*Ed. Pearson Ed. (zeta)


Session Storage and configuaration

Session Session Session

Sesson Session Session

Session Session

Server memory

Slides by Connolly & IJoar, "Fundamentals of Web Development" - 7’* id. Pearson Ed. (low)
Accessing session state
<?php
session start ;

i isse • S OF ' e ' )


User is og ed in

e se

st)

SIi‹1es by Connolly & I-Ioar, “F-undamentals of Web Development" - 2’*Ed. Pearson Ed, (2018)
Checking session existence
<?php

inc ude once "ShoppingCart.c ass. ";


session start ;

always check for existence o


session object before accessing i
i !isset SESSION "Cart"
session variables can be strings, t
arrays, or
objects, but smaller is better
SESSION "Cart" = new ShoppingCart ,

cart = SESSION "Cart" ;

Slitles by Connolly & Hoar, "Fundamentals of Web Development" - 2h*id. Pearson Ed, (2018)
Terminating a session

• Removing session variables


• Session_unset()
• Destroying the session
› session_destroy();
Information security
Risk Assessment and Management

• Actors, Impact, Threats, and


Vulnerabilities
Actors
• Internal actors are the people who work for the organization. They
can be anywhere in the organization from the cashier through the IT
staff, all the way to the CEO.
• External actors are the people outside of the organization. They
have a wide range of intent and skill, and they are the most
common source of attacks.
• Partner actors are affiliated with an organization that you partner or
work with. If your partner is somehow compromised, there is a
chance your data is at risk as well because quite often partners are
granted some access to each other's systems (to place orders, for
example).
Impact
• A loss of availability prevents users from
accessing some or all of the systems.
• A loss of confidentiality includes the
disclosure of confidential information to a
(often malicious) third party
• A loss of integrity changes your data or
prevents you from having correct data. This
might manifest as an attacker hijacking a
user session, perhaps placing fake orders
or changing a user's home address.
Security Principles

Threats
Broadly, threats can be categorized using the STRIDE mnemonic
• Spoofing—Theattacker uses someone else's information to access the system.
• Tampering—The attacker modifies some data in nonauthorized ways.
• Repudiation—The attacker removes all trace of their attack, so that they cannot be held
accountable for other damages done.
• Information disclosure—The attacker accesses data they should not be able to.
• Denial of service _The attacker prevents real users from accessing the systems.
• Elevation of privilege _ The attacker increases their privileges on the system
thereby getting access to things they are not authorized to do.
Vulnerabilities
• Vulnerabilities are the security holes in your system. The
top five classes of vulnerability from the Open Web
Application Security Project are:
1. Injection
2. Broken authentication and
session management
3. Cross-site scripting
4. Insecure deserialization
5. Security misconfiguration
Security Policy

• Usage policy defines what systems users are permitted to use, and under what
situations.
• Authentication policy controls how users are grantecl access to the systems.
• Legal policies define a wide range of things including data retention and backup policies as
well as accessibility requirements (like having all public communication well organized for
the blind).
Business Continuity
• Admin Password Management
• Backups and Redundancy
• Geographic Redundancy
• Stage Mock Events
• Auditing
Security by Design
Secure by Design

Ras;ulrameeO
Design
”irnplerrietttstton’

Privacy need5
Threat Testing
assessment
Pair
Security
po mming
Polcy Risk Security unit
assessment tests
Code Penetration
CAATriad reviews testing
Red ndancy Vulnerability
planning Pesos
Defensive
Attack thyse
programming
Test cases
Default
values
Authentication
Authentication Factors

t h a t you know (Knowledge)


Passwords, PIN, security questions, ...

t h a t you have (0 nership)


Access card, cell phone, cryptographic FOB, ...

t h a t you are ( nherence)


Retinas, fingerprints, DNA, walking gait, ...
Authentication Factors

• Single-factor authentication is the weakest


and most common category of
authentication system where you ask for
only one of the three factors.
• Multifactor authentication is where two
distinct factors of authentication must pass
before you are granted access.
HMP Authentication
• HTTP supports several diXerent forms of
authentication via the www- authenticate response
header.
• HTTP Basic Authentication
• HTTP Digest Authentication
• Form-Based Authentication
Third-Party Authentication

• Many popular services allow you to use their system to


authenticate the user and provide you with enough data
to manage your applicatiön
Third-Party Authenticaton - oAuth

Reso ce Client Authentication Resource


ner (your web server) server server

O Client egisteis

c l i e n t \ d , secret
Usei equests login page

Client redirects the user to authentication server with its ‹ Ii»‹ and
‹allba‹t URL

O Upon a valid login auiherticaiion servei ieiurns a


rediree t the client containing the authorization code.

Authorization code
Authorization code, secret
Aaess to en request
The client requests an
access token using
Access token (stored on client) the

O Use wants axess to


something.
Access token, resource request

The aaess token obtained eailiet grants aaess


to the iesoutce from the resource sewer.
oAuth
Third-Party Authentication

Resource Client Authentication Resource


owner (your web server) server server

O Client egisteis

c1 sent sd , secre t
Usei equests login page

I
O I
I
O Upon a valid login auihenticaiion servei ieiurns aredirect to the
client containing the authorization code.

Authorization code
Authorization code, secret 10
Aaess to en request
I The client requestsan
access tokenusing the
I Access token (stored on client) *’* ’I*! I* ’*'”"
'
UStf W6fltS 6tteSt to '
e h
*’ ’ ’' Access token, resource request

Protected resour‹r
The aaess token obtained eailiei grants accessto the
‹esource from the resource sewer.
Authorization

Authorization defines what rights and privileges a user has once they are
authenticated. Some principles:
• Using a separate database user for read and write privileges on a database.
• Providing each user an account where they can access their own files securely.
• Setting permissions correctly so as to not expose files to unauthorized users.
• Using Unix groups to grant users permission to access certain functionality rather than
grant users admin access.
• Ensuring Apache is not running as the root account (i.e., the account that can
access everythino).
WEEK 14
TOPIC 118 TO 126
Web Systems and Technologies
• 118 Cryptography, Cyphers, Digital Signatures
• 119 HTTPS
• 120 XML overview, XML Parser; XML schema
• 121 XSLT and XPath
• 122 XML Processing; XML in JavaScript; XML in PHP
• 123 JSON
• 124 Overview of Web Services
• 125 Consuming Web Services in PHP
• 126 Creating a Web Service in PHP
Web Systems and Technologies

Cryptography
Cryptography
An Overview

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Cryptography
Symmetric Encryption

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Cryptography
Modern Block Ciphers

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Cryptography
Public Key Cryptography

• Public key cryptography (or


asymmetric cryptography) solves the
problem of the secret key by using
two distinct keys: a public one, widely
distributed and another one, kept
private.

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Cryptography
Public Key Cryptography – Diffie Hellman

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Cryptography

Digital Signatures
• A digital signature is a
mathematically secure way of
validating that a particular digital
document was
• created by the person claiming to
create it (authenticity),
• was not modified in transit
(integrity), and
• cannot be denied (nonrepudiation).

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Cryptography
Digital Signatures

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

HTTPS
Hypertext Transfer Protocol Secure (HTTPS)

What the Browsers Say

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Hypertext Transfer Protocol Secure (HTTPS)

Secure Handshakes

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Hypertext Transfer Protocol Secure (HTTPS)

Certificates and Authorities

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Hypertext Transfer Protocol Secure (HTTPS)

Certificates and Authorities


• Certificate Authority (CA) allows users to place their trust in
the certificate since a trusted, independent third party signs
it.
• The CA’s primary role is to validate that the requestor of the
certificate is who they claim to be, and issue and sign the
certificate containing the public keys so that anyone seeing
them can trust they are genuine.
• In browsers, there are many dozens of CAs trusted by
default
• You can also self-sign certificates (generates warnings)
Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Hypertext Transfer Protocol Secure (HTTPS)

Certificates and Authorities

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Hypertext Transfer Protocol Secure (HTTPS)

Certificates and Authorities

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Hypertext Transfer Protocol Secure (HTTPS)

Migrating to HTTPS from HTTP


• Coordinating the migration of a website
can be a complex endeavor
• Mixed Content
• Internal links within the site.
• External links to frameworks delivered
through a CDN.
• Any links or references generated by PHP
code that might include a hardcoded http.
• References to http within any HTML markup
outside of PHP blocks.

• Redirects from old site


Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

XML Overview
XML Overview
Introduction
• XML is a markup language, but unlike HTML, XML can be used to mark
up any type of data
• One key benefit of XML data is that asplain text, it can be read and
transferred between applications and different operating systems
• XML is used on the web server to communicate asynchronously with
the browser
• Used as a data interchange format for moving information between
systems
XML Overview
• XML Usage
XML Overview
Well-Formed XML
• Element names are composed of any of the valid characters
• Element names can’t start with a number
• There must be a single-root element
• All elements must have a closing element (or
be self-closing)
• Elements must be properly nested
• Elements can contain attributes
• Attribute values must always be within quotes
• Element and attribute names are case sensitive
XML Overview
Well-Formed XML Simplified Example
<?xml version="1.0" encoding="ISO-8859-1"?>
<art>
<painting id="290">
<title>Balcony</title>
<artist>
<name>Manet</name>
<nationality>France</nationality>
</artist>
<year>1868</year>
<medium>Oil on canvas</medium>
</painting>
</art>
XML Overview
Valid XML

•A valid XML document is one that is well formed and whose


element and content conform to the rules of either its document
type definition (DTD) or its schema
• DTDs tell the XML parser which elements and attributes to expect
in the document as well as the order and nesting of those
elements
• A DTD can be defined within an XML document or within an
external file
XML Overview
Example Document Type Definition (DTD)

<?xml version="1.0" encoding="ISO-8859-1"?>


<?xml version="1.0" encoding="ISO-8859-1"?>
<art> <!DOCTYPE art [
<painting id="290"> <!ELEMENT art (painting*)>
<title>Balcony</title> <!ELEMENT painting
(title,artist,year,medium)>
<artist>
<name>Manet</name> <!ATTLIST painting id CDATA #REQUIRED>
<nationality>France</nationality> <!ELEMENT title (#PCDATA)>
</artist> <!ELEMENT artist (name,nationality)>
<year>1868</year> <!ELEMENT name (#PCDATA)>
<medium>Oil on canvas</medium> <!ELEMENT nationality (#PCDATA)>
</painting> <!ELEMENT year (#PCDATA)>
</art> <!ELEMENT medium (#PCDATA)>
]>
<?xml version="1.0" encoding="ISO-8859-1"?>

XML Overview <art>


<painting id="290">
<title>Balcony</title>

• Example XML Schema <artist>


<name>Manet</name>
<nationality>France</nationality>
</artist>
<year>1868</year>
<?xml version = "1.0" encoding = "UTF-8"?> <medium>Oil on canvas</medium>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema" </painting>
</art>
<xs:element name="art">
<xs:complexType>
<xs:sequence>
<xs:element name="painting" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:attribute type="xs:integer" name="id"/>
<xs:sequence>
<xs:element type="xs:string" name="title"/>
<xs:element name="artist">
<xs:complexType>
<xs:choice>
<xs:element type="xs:string" name="name"/>
<xs:element type="xs:string" name="nationality"/>
</xs:choice>
</xs:complexType>

</xs:element>
XML Overview
• Example XML Schema
<?xml version="1.0" encoding="ISO-8859-1"?>
<art>
<xs:element type="xs:short" <painting id="290">
<title>Balcony</title>
name="year"/> <artist>
<xs:element type="xs:string" <name>Manet</name>
<nationality>France</nationality>
name="medium"/> </artist>
</xs:sequence> <year>1868</year>
</xs:complexType> <medium>Oil on canvas</medium>
</painting>
</xs:element> </art>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Web Systems and Technologies

XPath and XSLT


XPath and XSLT
XPath
• XML Path Language
• Used for accessing elements and attributes in
an XML document
• Widely used in JavaScript for
accessing certain
elements/attributes of HTML documents
XPath and XSLT
XPath – Expressions

Expression Description
nodename All nodes with the name "nodename" painting
/ From root /art/painting
// Anywhere in the document
. Current node
.. Parent node
@ Attribute
[] Predicate
XPath and XSLT
XPath – Examples
<?xml version="1.0" encoding="ISO-8859-1"?>
<art>
<painting id="290">
• /art
<title>Balcony</title> • Selects element "art"
<artist>
<name>Manet</name>
<nationality>France</nationality>
• //year
</artist> • Selects element "year"
<year>1868</year>
<medium>Oil on canvas</medium>
</painting>
• //name/..
</art> • Selects element "artist"
• //painting/@id
• Selects attribute "id" in painting
• //painting[year>1800]
• Selects "painting" elements with
year > 1800
XPath and XSLT
XSLT

• eXtensible Stylesheet Language Transformation


(XSLT)
• Used for transforming an XML document into
another form
• Defined as an XML document
• Uses XPath for selecting elements and built-in
functions for processing/transforming them

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
XPath and XSLT
XSLT – Example
<?xml version="1.0" encoding="UTF-8"?>
XML XSLT <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/art">
<h1>Paintings</h1>
<ul>
XSLT Processor <xsl:for-each select="painting">
<li>
<xsl:value-of select="title"/> by
<xsl:value-of select="artist/name"/>
</li>
</xsl:for-each>
<h1>Paintings</h1> </ul>
<ul> </xsl:template>
<li>Balcony by Manet</li>
</ul>
</xsSldil :essbtyCyonlneolsy&hHeoeat
r ,">Fundamentalsof Web Development" - 2nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

XML Processing
XML Processing
XML Processing in JavaScript

• The in-memory approach, which


involves reading the entire XML file
into memory
• The event or pull approach, which
lets you pull in just a few elements or
lines at a time

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
XML Processing
XML Processing in JavaScript

var xmlhttp = new XMLHttpRequest()


xmlhttp.open("GET","art.xml",false);
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var paintings = xmlDoc.getElementsByTagName("painting");

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
XML Processing
XML Processing in jQuery
var art = '<?xml ...';

// create the DOM object


var xmlDoc = $.parseXML(art);

// convert DOM object to jQuery object var xml =


$(xmlDoc);

// find all the painting elements var


paintings = xml.find("painting");

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
XML Processing
XML Processing in PHP

• Can process XML using


• SimpleXML
• XMLReader

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
XML Processing
SimpleXML
<?php
$filename = 'art.xml';
if (file_exists($filename)) {
$art = simplexml_load_file($filename);
// access a single element
$painting = $art->painting[0];
echo '<h2>'.$painting->title.'</h2>';
}

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
XML Processing
XPath with SimpleXML
$art = simplexml_load_file($filename);
$titles = $art->xpath('/art/painting/title');
foreach ($titles as $t) {
echo $t . '<br/>';
}
$names = $art->xpath('/art/painting[year>1800]/artist/name');
foreach ($names as $n) {
echo $n . '<br/>';
}

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

JSON
JSON
Sample JSON

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
JSON
Using JSON in JavaScript

var text = '{"artist": {


"name":"Manet",
"nationality":"France"
}
}';
var a = JSON.parse(text); alert(a.artist.nationality);
//or a['artist']['nationality']

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
JSON
Using JSON in PHP
<?php
// convert JSON string into PHP object
$text = '{"artist": {
"name":"Manet", "nationality":"France"
}
}';
$anObject = json_decode($text);
// check for parse errors
if (json_last_error() == JSON_ERROR_NONE)
{
echo $anObject->artist->nationality;
}

?>
Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

Overview of Web Services


Overview of Web Services
Web Services

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Overview of Web Services

SOAP
Services

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Overview of Web Services
REST Services
/authors/1

Get Post
Put Delete

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Overview of Web Services
Identifying and Authenticating Service Requests

• Identity. Each web service request must


identify who is making the request.
• Authentication. Each web service request must provide additional
evidence that they are who they say they are.
• API Keys
• https://dev.virtualearth.net/REST/v1/Loca
tions?o=json&query=British%20Museum,
+Great+Russell+Street,+London,+WC1B
+3DG,+UK&key=[BING API KEY HERE]

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

Consuming Web Services


in PHP
Consuming Web Services in PHP
Consuming an XML Web Service

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Consuming Web Services in PHP
Consuming a JSON Web Service

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Consuming Web Services in PHP
Consuming a JSON Web Service

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Consuming Web Services in PHP
Consuming a JSON Web Service

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

Creating Web Services


Creating Web
Services
Creating a JSON Web Service

• Consider the URL and format of requests


• Tell the browser to expect JSON rather than
HTML
• Header('Content-Type: application/json');

• Use json_encode() to format.


• Implement JsonSerializable

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Creating Web Services
Creating a JSON Web Service
class Country extends DomainObject implements JsonSerializable
{
...
/*
This method is called by the json_encode() function that is part of PHP
*/
public function jsonSerialize() { return
['iso' => $this->ISO, 'name' => $this-
>CountryName, 'value' => $this->CountryName,
'area' => $this->Area, 'population' =>
$this->Population, 'continent' => $this-
>Continent, 'capital' => $this->Capital

]; } }

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Creating Web Services
Creating a JSON Web Service

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
WEEK 15
TOPIC 127 TO 135
Web Systems and Technologies

• 127-Web Services Using AJAX


• 128-JavaScript Frameworks
• 129-Node.JS
• 130-Simple Node.JS Program
• 131-Express.js, Routing in Express
• 132-Node.JS MYSQL
• 133-Introduction to Angular
• 134-Introduction to Web Sockets
• 135-Web Server Hosting
UsingGoogle maps

Asrc=apivJRh1=eu[5&›-°vO28;=?46?0z=l4
Ils c a1e=2 &s ty’1e= '0,37’L?^. sma ntnaps

A66iti0flal asynChF0 n0cIS FeqUKtS I0F til9s


JavaScript
Frameworks
JavaScript Frame work
JavaScript Frame work

JavaScript framework provide structure for developing


JavaScript applications

Popular frameworks
• Angular
• Ember
• Vue
• React
• Express
JavaScript for Backend Node.js

• Alternative to LAMP stack


• MEAN stack
MongoDB-Express-Angular-Node.js
• MERN stack
MongoDB-Express-React-Node.js
Introduction
• Started in 2009
› Runs Javascript outside the browser
• Uses Chrome V8 Javascript engine
• Javascript used to generate HTML code
• Uses non-blocking I/O
• Often used for server-side web
Development
Also used for non-web development,
Introduction
• Linkedln switched from Ruby on Rails to Node.js
• Up to 20 times faster
• Servers reduced from 30 to 3
• PayPal switched from Java to Node.js
• Developed in less time, with less
developers
• 33% less lines of code
• 40% less files
• Doubled performance (requests/second), with less processors
• Fast response time, 35% less response time
Push based web application

SIit1es by CDnnDIIy & I3oar, "Fundamental.s of Web Development" - 2'* Ed. Pearson Ed. (2018)
Blocking Thread-based Architecture (Traditional)
Each thread executes the
entirety of the web appII‹ation

and the generated


response is being
delivered (finally)

development" 2’ d Ed, Pearson Ld. (2 8)


Node.js Single-Thread
Architecture

asynchronousTy thus do not


block main event loop

These other tasks will


signal whin ready for
event loop response
Node Package Manager (NPM)

• Package manager for JavaScript


• Used for installing JavaScript libraries and frameworks
• Can handle dependencies
• Usage

npm install
npm install packagename
npm install packagename@version
npm update
npm list
Working with Node.js
// Load the http module to create an HTTP server
var http = require('http');

// Configure HTTP server to respond with Hello World to all requests var server =
http.createServer(function (request, response) {

response.writeHead(200, ("Content-Type": "text/plain"));


response.write("Hello this is our first node.js application\n"); response.end( );

)};

Listen on port 7000 on localhost server.listen(7000,


”localhost");

display a message on the terminal

Console.log(“server running at http://127.0.0.1:7000/”);


Working with Node.js

$ me hc11 o. §s
running
F›rst you have to run the program via node command (You
can stop the program via Ctrl-CQ

Then use browser to request URL and port


He1la thIs £s our I tr st node. §s applI catI on

Note: every time you make a change o your Node


source file, you will have to stop the program and re-
run i ,

Slides by ConnDlly & Hour, "Fundamentals of Web Development" • 2’.*’8d.:Paafaoc"Ed:.!(0ét8)


Example

• Writing to a file
data is written in the file 'message.txt'
When writing is complete, anonymous function is "called back"

const fs = require('fs')
(e r r) {
fs.writeFile('message.txt'
' Hel l o No rl d ! ' , f u n c t i on
i f (e r r)
consol e . er ro r (e r r) ;
process.exit(1);
consol e . I og ( Nri ti ng i s done .
Introduction
Minimalist web application framework for Node.js
• Handles
• Routes
• Requests/Responses
• Views
Example
express require('express')
app express()
const port 7OOO

app.get('/:me', function(req, re )
res.send('Hello '.req.params.name)

function
console.log( ”http://localhost:”.$(port
Introduction
• Mostly Node.js is used with NoSQL databases like
MongoDB
• Can be used with traditional DBMS like mysql
Example
Var require('mysql');
var sql ='SELECT * FROM books';

Var con = mysql.createConnection({


Host :"localhost",
user:“root",
password:“”,

});

con.connect(function(err) {
If (err) throw err; console.log("Connected!” ,
con.query(sql, function (err, result
If (err) throw err; console.log("Result:“ + result);
});
});
Introduction

• Angular is a popular browser-based, open-source JavaScript


MVC framework (Google driven)
• It is the A’ in the MEAN stack, independent of the other
components of the stack, and can be used without
any of them
• Angular allows developers to write in TypeScript, JavaScript,
or Dart
• AngularJS uses JavaScript
• Well suited for single page applications
Creating Simple AngularJS Application
20</t1 t1 e»
<scr1pt src="https : / / code . angul arj s . org/ 1.5. 0/ angu1 ar . nt n . j s" »
•/scr4pt
<htm1A rftrr'r 'vr' [‹›r \ c'si‹ Fi.z l'ii jr [[ u F‹Jc›t Au tu Iz›rJS ‹*lc'mui’ t
ng - app>
< / haad>
head»
<body>
<t1 t1e»Chapter A cliv r'cfi«: fui suvirjcj I Iss' [iel‹J vulur' in the' Mc›cJc'l
Enter
type=" t e x t " ng -‹r‹›del = "name" / >
<p>You your name: <1nput
ant ered : { ( name )} */ p>

<hr>
Enter you r c i ty : <1nput type="tex t ” nq model = "c i I y ' / >
<p>You entered : t ‹:1 I y ) ) < / p»
</ body>
/html•

Appears as user types into textbox


Slides Ivy Curii oily & I I‹» r, "I-r‹ndamentaIs of Web Development" - 2’* Ed. Pearson Ed. (does)
A Controller

A moc1ril+ is an Arig oil ar JS con t‹aiiler fnr the if Ierm t Ann /›an+nIs feed in the ap licaI ion
Nuw lI+is dit’e‹:Iive is spec i I yii›q the rriodu/c' used in the all lice I iun
•html ng app= 'dewo"• va r riyapp = angu1ar . riodul e ( ' demo' , [ ] ) ;
The $ s c‹›t›‹* va i.at›le is pa semi Tinjectert iiltc›)
Th is elt› we n t i s g n i n g IO Add a controller to the modLllL' f1. iOd mgCon I rol Jer fhc controller l›y Anq«I.arJS
;Sfi fi COnI rO/fer IO get iIS rJata

<body ng - con t ro 11or- " "» nyapp , cont ro11er ( @g $t* I ' , f unct 1on ($scope) (
<d1v 1 d= " 868f'ch * » Srive tl\r user's ink bit in ‹ ‹nndel prnt›erty n«+›’i‹•ct search $acope . c1I es = [ (name: ' Ca1gary ' , ' count ry : Canada ' ) ,
C1ty Search : <1nput (name:
type="I ext ” ng - ncde T- seure I› /> The s ‹'‹›t›o vari‹r+ i› v›‹.u i TDFent o , ' count ry : ' Canada ' } ,
• / d1v> (name: Boat on ' , count ry: ' 0n1 ted States ) ,
(name: ' Seat t1 e ' , ' count ry
s t ab 1 e» A directive to loop thruuqh a co\ Iectic›n namecT c I r 1os (whirh is de fir\ed in the controller) Un1ted Stat6B ' ) ,
(name: ATmar a’ , count ry :
<tr ng - Fepeat="c1 t y Jn c t as | H1 t ar sea re I | or do rBy ' nama ' ">
(name: ’Spaln ' } ,
«td» ( c1t , f1n‹re ) ) < / td> q /,// tn nlter lagw Fhis ¢'Ieicc'nt works. In this ' Berca \ ona ' , count ry: ' Spa1n ' ) ] ;

< / t r» data bind tn values In II c


• /t b1 › collcc tlon

</ body»
The res«It in tf›e browser (notice the sort order)
</ htm1 »

Searcf› text fiRld.

Slides by ConnDIIy & I-Ioar, "Fundamentals of Web Development" - 3ndEd. Pearson Ed. (2018)
Getting Data from a Web Service

var myapp = angular.module('demo',[ ]),


//notice that our callback function is passed the $http parameter.
//parameters are injected by the AngularJS system "behind-the-scenes"
myapp.controller('myController', function (6scope, $http)

//retrieve country data from web service


Var url =' http://randyoonnolly.com/funwebdev/services/travel/countries.php†continent=EU;'

$http.get(url).then(function (response)
$scope.countries= response.data
});
});
Web sockets
Introduction

• Web socket is a full duplex


communication protocol
• Enables interaction between web
browser and web server
Server Side Example (Node.js)
e xsps re .r equ i re ( ' e xp re s s ' ) ;
con s t app expre s s () ;

server hLtp.oreaLeServor(app);
cons Server require("socket.io
t (socket)
");
cons console.log('A user connested'),));
new Server(scrver);
t function(message) console.log('Mcssage
from client: '+messago): io.emit('Message received
'+message}),

L : 7 000 ); ))/
Client Side Example (JavaScript)

var client new WebSocket("http://localhost:7000");

//sending message on socket open


clienL.onopen
clicnt.send("Mcssagc the sorver");

//receiving message
ol i en L . o u n c e ringe c I un t. i o n ( e ve n L)
conso lo . 1oq (event . ‹data) ;

se connection
Web server Hosting
Hosting Types

• Shared Hosting
• Simple
• Virtualized

• Dedicated
• Collocated
• In-house
• Cloud
WEEK 16
TOPIC 136 TO 144
Web Systems and Technologies

• 136 Domain and Name Server Administration


• 137Search Engines
• 138Page Rank
• 139Search Engine Optimization
• 140Understanding Bad SEO
• 141Introduction to Online Social Networks
• 142Monetization with Ads
• 143Web Analytics
• 144 Google Analytics
Web Systems and Technologies

Domain and Name Server


Administration
Domain and Name Server Administration

Introduction
• Domain Name System (DNS) is used to resolve an IP
address of a website
• Domain name registrars register website
• GoDaddy
• TuCows
• Network Solutions
Domain and Name Server Administration

DNS
• Registration
• WHOIS
• Use whois command
• Private registration
• Updating name servers
• Takes up to 48 hours
• Check status using dig command
• https://toolbox.googleapps.com/apps/dig
• Reverse DNS
Domain and Name Server Administration

DNS Record Types


• Mapping (A/AAA)
• Mail Exchange (MX)
• Authoritative (NS/SOA)
• Validation (TXT/SPF)
Web Systems and Technologies

Search Engines
Search Engines
Introduction
• Before the search engines
• Emails, message boards, websites
• Web directories (vlib, yahoo, dmoz)
• Web Crawlers
• Google
Search Engines
Search Engine Overview
• Components of a search engine
• Web Crawler, URL submission, …
• Indexes
• Query Server
Web Systems and Technologies

PageRank
PageRank
• PageRank
• An algorithm for ranking websites
• Models WWW as a graph, example:
HEC MOE • On VU website
<a href=‘https://hec.gov.pk’>HEC</a>
• On QAU website
<a href=‘https://hec.gov.pk’>HEC</a>

QAU VU
• On HEC’s website
<a href=‘https://vu.edu.pk’>VU</a>
<a href=‘https://qau.edu.pk’>QAU</a>
<a href=‘https://mofept.gov.pk’>MOE</a>
PageRank
PageRank

• Pages pointed by important pages are


important

Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
PageRank
How PageRank Works

HEC VU QAU MOE

HEC MOE
Iter 0 ¼ ¼ Iter 1 ¼ 1/4

¼+ ¼=1/2 1/12 1/12 1/12


QAU VU
Iter 2

Web Systems and Technologies

Search Engine
Optimization
Search Engine Optimization
Introduction
• Search Engine Optimization(SEO) is a way
to increase the rank of a website
• White hat SEO
• Black hat SEO
Search Engine Optimization

White-Hat SEO Techniques


• Title and Meta-data
• Title, description, robot
/users/id/123

• Designing URLs
• Descriptive paths and file names

• Website Design
• Layout, readability, JavaScript, structure

• Sitemaps

• Anchors and Images


• Anchor text, image name, alt

• Contents
• Original, fresh, UGCs
Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2 nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

Black Hat SEO


Search Engines
Introduction

• Try to exploit search engine rankings


• Should not be used
Search Engines
Black-Hat SEO Techniques
• Content spamming
• Keyword stuffing, hidden content, paid links, doorway
pages

• Link spam
• Hidden links, comment spam, link farms, and pyramids, google
bombing

• Google bowling
• Cloaking
• Duplicate Contents
Web Systems and Technologies

Online Social Networks


Online social Networks
Introduction
• Social networks
• Free usage
• User profile
• Monetization
• Extensive API support
Online social Networks
Social Media Presence
• Home pages on social media platforms
• Link and logos
• Using URL shorteners
Online social Networks

Facebook Plugins
• Register as a developer
• Facebook Markup Language(FBML)
• Like and recommend buttons
<div class=“fb-like”
data-href=“https://example.com/page.html”
data-width=“200”
data-layout=“standard” data-action=“like”
data-size=“small”
data-share=“true”>

</div>

• More plugins
https://devolopers.facebook.com/docs/plugins
Online social Networks
Twitter Widgets
• Twitter
• Widgets
• Tweet this button
<a class=“twitter-share-button”

href=https://twitter.com/intent/tweet?text=Hello World!”>Tweet</a>

<script async

src=https://platform.twitter.com/widgets.js charset=“utf-8”></script>

• More widgets
https://publish.twitter.com
Web Systems and Technologies

Monetization with Ads


Monetization with Ads
Introduction
• Ads on a website can generate revenue
• How web ads work?
• Ad Networks
Monetization with Ads
Ad Types
• Ad types
• Graphics
• Text
• Dynamic
Monetization with Ads
Creating Ads
• Register for a Google AdSense (or other
account)
• Get code through AdSense account
• Place it on your website
Monetization with Ads
Web Ads Economy
• Ad Commodities
• Views
• Clicks
• Actions

• Web Commodity markets


• Cost Per Click(CPC)
• Cost Per Mile (CPM)
• Cost Per Action(CPA)
• Click Through Rate (CTR)

• Auctions
Slides by Connolly & Hoar, "Fundamentals of Web Development" - 2nd Ed. Pearson Ed.
(2018)
Web Systems and Technologies

Web Analytics
Web Analytics
Introduction
• Web analytics provide us insights about website
usage
• Bandwidth usage
• Referrers
• Popular domains/page
• Search terms used for landing
• User behavior
• Demographics
Web Analytics
Web Metrics
• Page Views
• Unique page views
• Average visit duration
• Bounce rate
Web Analytics
Internal Analytics
• IP address
• User agent analysis
• Frequency analysis
• Can be provided by hosting company
Web Analytics
Third Party Analytics
• Google, Bing, …
• Dashboards
• Flow analysis
• In-page analytics
Web Systems and Technologies

Google Analytics-Demo

You might also like