0% found this document useful (0 votes)
19 views98 pages

Understanding Web Server Functionality

The document provides an overview of web servers, detailing their functions, types, and how they handle client requests. It also discusses dynamic content generation using PHP, including its syntax, variables, and data types. Additionally, it covers techniques to manage server overload and the importance of comments in PHP code.

Uploaded by

simantakasaju
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)
19 views98 pages

Understanding Web Server Functionality

The document provides an overview of web servers, detailing their functions, types, and how they handle client requests. It also discusses dynamic content generation using PHP, including its syntax, variables, and data types. Additionally, it covers techniques to manage server overload and the importance of comments in PHP code.

Uploaded by

simantakasaju
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

Chp:4

The Server Tier


Prepared by: Er. Simanta Kasaju

Er. Simanta Kasaju 1


Web Server Concept

• Web server is a computer where the web content is stored.


• Web server is a computer system which receives the HTTP request via TCP, which are used
to distribute information on www.
• Commonly a web browser or web crawler initiates communication by making HTTP request for a
specific resource and the server response with the content of that resource or an error message if
unable to do so.
• Basically web server is used to host the web sites but there exists other web servers also such as
gaming, storage, FTP, email etc.
• Web site is collection of web pages while web server is a software that respond to the request for
web resources.

Er. Simanta Kasaju 2


Cont.
• The main function of a web server is to store, process and deliver web pages to clients. The
communication between client and server takes place using the HTTP.
• Pages delivered are most frequently HTML documents, which may include images, stylesheets
and scripts in addition to text content.
• Web servers are not always used for serving the www. They can also be found embedded in
devices such as printers ,routers, webcams and serving only a local network.

Er. Simanta Kasaju 3


Web Server Working
• Web server respond to the client request in either of the following two ways:
• Sending the file to the client associated with the requested URL.
• Generating response by invoking a script and communicating with database

Key Points
•When client sends request for a web page, the web
server search for the requested page if requested page
is found then it will send it to client with an HTTP
response.
•If the requested web page is not found, web server will
the send an HTTP response: Error 404 Not found.
•If client has requested for some other resources then
the web server will contact to the application server and
data store to construct the HTTP response.
Er. Simanta Kasaju 4
Examples: Following table describes the most leading web servers available today:

S.N. Web Server Description

1 Apache HTTP Server


This is the most popular web server in the world developed by the Apache Software Foundation. Apache web server is an open
source software and can be installed on almost all operating systems including Linux, UNIX, Windows, FreeBSD, Mac OS X and
more. About 60% of the web server machines run the Apache Web Server.
2. Internet Information Services (IIS)
The Internet Information Server (IIS) is a high performance Web Server from Microsoft. This web server runs on Windows
NT/2000 and 2003 platforms (and may be on upcoming new Windows version also). IIS comes bundled with Windows NT/2000
and 2003; Because IIS is tightly integrated with the operating system so it is relatively easy to administer it.
3. Lighttpd
The lighttpd, pronounced lighty is also a free web server that is distributed with the FreeBSD operating system. This open
source web server is fast, secure and consumes much less CPU power. Lighttpd can also run on Windows, Mac OS X, Linux and
Solaris operating systems.
4. Sun Java System Web Server
This web server from Sun Microsystems is suited for medium and large web sites. Though the server is free it is not open
source. It however, runs on Windows, Linux and UNIX platforms. The Sun Java System web server supports various languages,
scripts and technologies required for Web 2.0 such as JSP, Java Servlets, PHP, Perl, Python, and Ruby on Rails, ASP and
Coldfusion etc.
5. Jigsaw Server
Jigsaw (W3C's Server) comes from the World Wide Web Consortium. It is open source and free and can run on various
platforms like Linux, UNIX, Windows, and Mac OS
[Link]
Free BSD etc. Jigsaw has been written in Java and can run CGI scripts
Kasaju 5 and
PHP programs.
Load limits
• A web server has defined load limits. It can handle only a limited number of concurrent client
connections and it can serve only a certain maximum number of requests per second depending
on.
• Its own setting
• Hardware and software limitation of OS
• HTTP request type
• Content origin(static or dynamic) etc.

When a web server is near to or over its limits ,it becomes unresponsive.

Er. Simanta Kasaju 6


Overload cause
At any time web servers can be overloaded because of
• Too much web traffic: when millions of clients connecting to the web site in a short interval
overloaded can occur.
• Distributed Denial of service attacks
• Computers worms that sometimes cause abnormal traffic because of millions of infected
computers
• Web servers partial unavailability. This can happen because of required or urgent maintenance or
upgrade, hardware or software failures, back end(eg database) failures etc, In these cases the
remaining web servers get too much traffic and become overloaded.
• Internet connection slowdowns, so that client requests are served more slowly and the number
of connections increases so much that server limits are reached

Er. Simanta Kasaju 7


Anti-overloaded technique
To partially overcome load limits and to prevent overload we can use techniques
like:
- Managing network traffic by using:
• Firewalls to Block unwanted traffic coming from bad IP sources,
• HTTP traffic managers to drop , redirect or rewrite requests having bad HTTP
patterns
• Bandwidth management and traffic shaping
- Deploying web cache techniques
• Use different domains to serve different content (static and dynamic) by separate
Web servers
• Add more hardware resources
• Use many web servers

Er. Simanta Kasaju 8


Using control flow to control dynamic
content generation
• Dynamic content in the context of HTML and the World Wide Web refers to website content that
constantly or regularly changes based on user interactions, timing and other parameters that determine
what content is delivered to the user.
• This means that the content of the site may differ for every user because of different parameters.
• Facebook is an excellent example of a site that delivers dynamic content, as every user gets different
content based on their friends and social interactions, although the layout stays generally the same.
• This could be different text, video, advertisements or even an entirely different layout and color.
• Any element in a page which contains movement and can change over time may be considered as
dynamic content.
There are two ways to provide dynamic content:
1. Using client-side scripting and frameworks such as JavaScript, AJAX and Bootstrap to change the UI
behavior within a specific Web page in response to specific user actions and timings. This gives dynamic
behavior to the UI presentation. This is normally used in Web applications and interactive
websites. Er. Simanta Kasaju 9
Cont..
• 2. Using server-side scripting and processing to dynamically form both the layout and content to
be delivered to the user based on parameters such as the user’s location, time of day, browser
being used or user preferences.
• Some good examples of this are social networking sites and content delivery sites.
• Social networking sites such as Facebook and Twitter provide entirely different content per user
because of the difference of their connections and subscribed services, while sites like YouTube
and Amazon provide dynamic content based on user-specific preferences based on past
purchases or views; the server gives suggested items or content that the user may like based on
historical data.

Er. Simanta Kasaju 10


What is PHP?

• PHP is an acronym for "PHP: Hypertext Preprocessor"


• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the browser as plain HTML
• PHP files have extension ".php"

Er. Simanta Kasaju 11


What Can PHP Do?

• PHP can generate dynamic page content


• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
• With PHP you are not limited to output HTML. You can output images, PDF files,
and even Flash movies. You can also output any text, such as XHTML and XML.

Er. Simanta Kasaju 12


Basic PHP Syntax
•Example​
<!DOCTYPE html>​
<html>​
• A PHP script can be placed anywhere in the document. <body>​
• A PHP script starts with <?php and ends with ?>:
<h1>My first PHP
• <?php
// PHP code goes here page</h1>​
?>
<?php​
• The default file extension for PHP files is ".php". echo "Hello World!";​
• A PHP file normally contains HTML tags, and some PHP scripting code. ?>​
• Below, we have an example of a simple PHP file, with a PHP script that
uses a built-in PHP function "echo" to output the text "Hello World!" </body>​
on a web page: </html>

Er. Simanta Kasaju 13


sample
<html>
<body>
<?php <?php
echo "I m studying php"; $txt = "PHP";
echo "I m studying $txt";
?> ?>
</body>
</html>

Er. Simanta Kasaju 14


Comments in PHP
• A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.
• Comments can be used to:
• Let others understand your code
• Remind yourself of what you did - Most programmers have experienced coming back to their own
work a year or two later and having to re-figure out what they did. Comments can remind you of
what you were thinking when you wrote the code
• PHP supports several ways of commenting:
// This is a single-line comment

# This is also a single-line comment /*


This is a multiple-lines comment block
that spans over multiple
lines
*/
Er. Simanta Kasaju 15
PHP Variables
• Variables are "containers" for storing information
• In PHP, a variable starts with the $ sign, followed by the name of the variable:
<?php
$txt = "Hello PHP Variables
world!"; A variable can have a short name (like x and y) or a more descriptive name
$x = 5; (age, carname, total_volume).
$y = 10.5; 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 ($age and $AGE are two different
variables)

Er. Simanta Kasaju 16


Output Variables

• The PHP echo statement is often used to output data to the screen.
• The following example will show how to output text and a variable:

<?php <?php
$txt = "[Link]"; 9
$x = 5;
echo "I love $txt!"; $y = 4;
?> echo $x + $y;
?>

<?php
$txt = "[Link]";
echo "I love " . $txt . "!";
?>

Er. Simanta Kasaju 17


PHP Variables Scope

• In 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:
• local
• global
• static

Er. Simanta Kasaju 18


Global and Local Scope
• A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function:

<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will
generate an error
echo "<p>Variable x inside function is:
$x</p>";
}
myTest();

echo "<p>Variable x outside function is:


$x</p>";
?>
Er. Simanta Kasaju 19
LOCAL SCOPE
• A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside
function is: $x</p>";
}
myTest();

// using x outside the function will


generate an error
echo "<p>Variable x outside function
is: $x</p>";
?>
Er. Simanta Kasaju 20
PHP echo and print Statements
• echo and print are more or less the same. They are both used to output data to the screen.
• The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare) while print can
take one argument. echo is marginally faster than print.

<?php
echo "<h2>PHP is
Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn
PHP!<br>";
echo "This ", "string ", "was
", "made ", "with multiple
parameters.";
?>
Er. Simanta Kasaju 21
PHP Data Types

• Variables can store data of different types, and different data types can do different
things.
• PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

Er. Simanta Kasaju 22


PHP String

• A string is a sequence of characters, like "Hello world!".


• A string can be any text inside quotes. You can use single or double quotes:

<?php
$A="are u learning";
echo var_dump($A);
?>

Er. Simanta Kasaju 23


PHP Integer
• An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
• Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2)
notation

<?php
$x = 5985;
var_dump($x);
?>

Er. Simanta Kasaju 24


PHP Float

• A float (floating point number) is a number with a decimal point or a number in exponential form.
• In the following example $x is a float. The PHP var_dump() function returns the data type and
value:

<?php
$x = 10.365;
var_dump($x);
?>

Er. Simanta Kasaju 25


PHP Boolean

• A Boolean represents two possible states: TRUE or FALSE.


• $x = true;
$y = false;
• Booleans are often used in conditional testing.

$A=true;
echo var_dump($A);

Er. Simanta Kasaju 26


PHP Array

• An array stores multiple values in one single variable.


• In the following example $cars is an array. The PHP var_dump()
function returns the data type and value:

<?php
$cars =
array("Volvo","BMW","Toy
ota");​
var_dump($cars);​
?>

Er. Simanta Kasaju 27


PHP Object
• Classes and objects are the two main aspects of object-oriented programming.
• A class is a template for objects, and an object is an instance of a class.
• When the individual objects are created, they inherit all the properties and behaviors from the
class, but each object will have different values for the properties.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("black", "Volvo");


echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>

Er. Simanta Kasaju 28


PHP NULL Value

• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
• Variables can also be emptied by setting the value to NULL:
<!DOCTYPE html>
<html>
<body>
<?php NULL
$x = null;
var_dump($x);
?>
</body>
</html>
Er. Simanta Kasaju 29
PHP Resource

• The special resource type is not an actual data type. It is the storing of
a reference to functions and resources external to PHP.
• A common example of using the resource data type is a database call.
• We will not talk about the resource type here, since it is an advanced
topic.

Er. Simanta Kasaju 30


PHP Operators

Operators are used to perform operations on variables and values.


PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators

Er. Simanta Kasaju 31


PHP Arithmetic Operators

Er. Simanta Kasaju 32


PHP Assignment Operators

Er. Simanta Kasaju 33


PHP Comparison Operators

Er. Simanta Kasaju 34


PHP Increment / Decrement Operators

Er. Simanta Kasaju 35


PHP Logical Operators

Er. Simanta Kasaju 36


PHP String Operators

Er. Simanta Kasaju 37


PHP Array Operators(The PHP array operators are used to
compare arrays.)

Er. Simanta Kasaju 38


PHP Conditional Assignment Operators

Er. Simanta Kasaju 39


Case insensitive
PHP Constants define("GREETING", "Welcome to
[Link]!", true);

• PHP Constants
• A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
• A valid constant name starts with a letter or underscore (no $ sign before the constant name).
• Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
• To create a constant, use the define() function. Case sensitive
<?php
• Syntax define("GREETING", " Welcome to [Link]!
• define(name, value, case-insensitive) Welcome to
• Parameters: [Link]!");
• name: Specifies the name of the constant echo GREETING;
?>
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

Er. Simanta Kasaju 40


PHP Constant Arrays
• In PHP7, you can create an Array constant using the define() function.

<?php
define("cars", [
"Alfa Romeo",
"BMW", Toyota
"Toyota"
]);
echo cars[2];
?>

Er. Simanta Kasaju 41


PHP Conditional Statements
• Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.
• In PHP we have the following conditional statements:
• if statement - executes some code if one condition is true
• if...else statement - executes some code if a condition is true and another code if that
condition is false
• if...elseif...else statement - executes different codes for more than two conditions
• switch statement - selects one of many blocks of code to be executed

Er. Simanta Kasaju 42


PHP - The if Statement
• The if statement executes some code if one condition is true.
• Syntax
• if (condition) {
code to be executed if condition is true;
}
<?php
$t = 40;

if ($t <"45") { congratulation


echo "congratulation";
?>

Er. Simanta Kasaju 43


PHP - The if...else Statement
• The if...else statement executes some code if a condition is true and another code if that
condition is false.
• Syntax
<?php
• if (condition) { $t = 40;
code to be executed if condition is true;
} else { if ($t >"45") {
code to be executed if condition is false; echo "congratulation"; sorry
} }
else
echo "sorry ";
?>

Er. Simanta Kasaju 44


PHP - The if...elseif...else Statement
• The if...elseif...else statement executes different codes for more than two conditions.
• Syntax
<?php
• if (condition) {
code to be executed if this condition is true; $t = 40;
} elseif (condition) {
code to be executed if first condition is false and this condition is true; if ($t >"90") {
} else { echo "A+";
code to be executed if all conditions are false; } fail
} else if($t <"85" &&
$t>"80"){
echo "B+ ";}
else
echo "fail";
?>

Er. Simanta Kasaju 45


The PHP switch Statement
• Use the switch statement to select one of many blocks of code to be executed.
• Syntax
• switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
• This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the
expression is then compared with the values for each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.
Er. Simanta Kasaju 46
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue": Your favorite color is red!
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, nor green!";
}
?>

Er. Simanta Kasaju 47


PHP Loops
• Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use
loops.
• Loops are used to execute the same block of code again and again, as long as a certain condition
is true.
• In PHP, we have the following loop types:
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
• The following chapters will explain and give examples of each loop type.

Er. Simanta Kasaju 48


The PHP while Loop
• The while loop executes a block of code as long as the specified condition is true.
• Syntax
• while (condition is true) { The number is: 0
code to be executed; The number is: 10
} <?php The number is: 20
$x = 0; The number is: 30
The number is: 40
<?php while($x <= 100) { The number is: 50
$x = 1; echo "The number is: $x The number is: 60
<br>"; The number is: 70
while($x <= 5) { The number is: 1 $x+=10; The number is: 80
echo "The number is: $x <br>"; The number is: 2 } The number is: 90
$x++; The number is: 3 ?> The number is: 100
} The number is: 4
?> The number is: 5

Er. Simanta Kasaju 49


The PHP do...while Loop
• The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
• Syntax
• do {
code to be executed;
} while (condition is true);
<?php
$x = 6;
<?php
$x = 1; The number is: 6
do {
echo "The number is: $x
do {
The number is: 1 <br>";
echo "The number
The number is: 2 $x++;
is: $x <br>";
The number is: 3 } while ($x <= 5);
$x++;
The number is: 4 ?>
} while ($x <= 5);
?> The number is: 5
Er. Simanta Kasaju 50
The PHP for Loop
• The for loop is used when you know in advance how many times the script should run.
• Syntax
• for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
• Parameters:
• init counter: Initialize the loop counter value
• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value

Er. Simanta Kasaju 51


The number is: 0
<?php The number is: 1
for ($x = 0; $x <= 10; $x++) The number is: 2
{ The number is: 3
echo "The number is: $x <?php
The number is: 4
<br>"; for ($x = 0; $x <= 100;
The number is: 5
} $x+=10) {
The number is: 6
?> echo "The number is: $x
The number is: 7
<br>"; The number is: 0
The number is: 8
} The number is: 10
The number is: 9
?> The number is: 20
The number is: 10
The number is: 30
The number is: 40
The number is: 50
The number is: 60
The number is: 70
The number is: 80
The number is: 90
The number is: 100

Er. Simanta Kasaju 52


Session & State
• Web is stateless that means the web browser does not know who you are
and what you do,because the HTTp address doesn’t maintain [Link] user
inserts some information and move to the next page that data will be lost
and user would not able to retrive the [Link] we need to store the
information about user.
• Session provides that facility to store information on server memory.
• A session is a way to store information(in variables) to be used across
multiple pages.
• Session variables hold information about one single user and are available
to all pages in one application.
• By default session variables last until the user closes the browser.

Er. Simanta Kasaju 53


Cont..
• Unlike a cookie, the information is not stored on the users computer.
• We all know that the web uses the HTTP protocol and the HTTP
protocol is a stateless protocol; in other words, when a client sends a
request to the server, an instance of the page is created and the page
is converted to HTML format and then the server provides the
response and then the instance of the page and the value of the
control are destroyed.
• So if we have a requirement to store the values of the controls and
pass them into another web form then a State Management
Technique is used.

Er. Simanta Kasaju 54


Cont..
• Session is a State Management Technique. A Session can store the
value on the Server.
• It can support any type of object to be stored along with our own
custom objects.
• A session is one of the best techniques for State Management
because it stores the data as client-based, in other words the data is
stored for every user separately and the data is secured also because
it is on the server.

Er. Simanta Kasaju 55


Cont..

Er. Simanta Kasaju 56


Cont..
• State management using session is one of the best features, because it is
secure, transparent from users, and we can store any kind of object in it.
• Along with these advantages, some times session can cause performance
issues in high traffic sites because it is stored in server memory and clients
read data from the server.

Er. Simanta Kasaju 57


Advantages

• It helps maintain user state and data all over the application.
• It is easy to implement and we can store any kind of object eg.
Database, dataset etc.
• Stores client data separately.
• Session is secure and transparent from the user.

Er. Simanta Kasaju 58


Disadvantages
• As session is stored on the server memory, it is not advisable to use session
state when there is a large volume of data.
• With the use of session state, it will affect the performance of memory,
because it is stored in server memory until you destroy the state
• The problem with sessions is that when you close your browser you also lose
the session so, if you had a site requiring a login, this couldn't be saved as a
session like it could as a cookie, and the user would be forced to re-login
every time they visit.

Er. Simanta Kasaju 59


Creating a session
• Simply by calling the session_start() function you can create a new
[Link] variables are set with the PHP global: $_SESSION.
Syntax:
Session_start();
This is the initialization of [Link] and every page at the top
script,we must initiate the session,if we need anhy session value.
Syntax:
$_SESSION['session_name]="value";

Er. Simanta Kasaju 60


Example
• <?php
// Start the session Note: The session_start() function must be
session_start(); the very first thing in your document.
?> Before any HTML tags.
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat"; Session variables are set.
echo "Session variables are set.";
?>
</body>
</html>

Er. Simanta Kasaju 61


Retrieving the value from session
• <?php
session_start(); We can retrive the value in any page if we
?> store the value in [Link] carries
<!DOCTYPE html> the values drom one page to another
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html> Favorite color is .
Favorite animal is .

Er. Simanta Kasaju 62


To view variables
Modify a PHP Session
• <?php Variable
session_start();
?>
<?php
<!DOCTYPE html> // to change a session variable, just
<html> overwrite it
<body> $_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
<?php ?>
print_r($_SESSION);
?>
</body>
</html>
Er. Simanta Kasaju 63
Destroy a PHP Session
• <?php
session_start();
?> To remove all global session variables and
<!DOCTYPE html> destroy the session,
<html> use session_unset() and session_destroy():
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

Er. Simanta Kasaju 64


Session ID
• When a client communicates with a server, only the session ID is
transmitted between them. When the client requests for data, [Link]
looks for the session ID and retrieves the corresponding data. This is done
in the following steps:
• Client hits the web site and information is stored in the session. Server
creates a unique session ID for that client and stores it in the Session State
Provider.
• The client requests for some information with the unique session ID from
the server.
• Server looks in the Session Providers and retrieves the serialized data from
the state server and type casts the object

Er. Simanta Kasaju 65


Client Web Server State Provider

-Creates secure
-Request for Pages session ID and store
and want to store data in state Store client data
some information' provider separately
-Next time clients -Server takes the Send data to server
request again for seesion ID to based on session ID
some information session State
provider

Er. Simanta Kasaju 66


Only
the name parameter
PHP Cookies is required. All other
parameters are
optional.
• A cookie is often used to identify a user.
• A cookie is a small file that the server embeds on the user's computer. Each time the same
computer requests a page with a browser, it will send the cookie too. With PHP, you can both
create and retrieve cookie values.
• Create Cookies With PHP
• A cookie is created with the setcookie() function.
• Syntax
• setcookie(name, value, expire, path, domain, secure, httponly);
• Only the name parameter is required. All other parameters are optional.

Er. Simanta Kasaju 67


Cretation of cookies
<?php
$cookie_name="Admin";
$cookie_value="Simanta Kasaju";
setcookie($cookie_name,$cookie_value,time()+(86400),"/");
?>
<html>
<body>
<?php
echo $_COOKIE[$cookie_name];
?>
</body>
</html>

Er. Simanta Kasaju 68


We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We
also use the isset() function to find out if the cookie is set:
<?php
<?php
$cookie_name="Admin"; $cookie_name = "Admin";
$cookie_value="Simanta Kasaju"; $cookie_value = "Prashant Kasaju";
setcookie($cookie_name,$cookie_value,time()+(86400*30)," setcookie($cookie_name, $cookie_value,
/"); time() + (86400 * 30), "/");
?> ?>
<html> <html>
<body> <body>
<?php
<?php
if(!isset($_COOKIE[$cookie_name]))
if(!isset($_COOKIE[$cookie_name])) {
{ echo "is not set!";
echo "not set"; } else {
} $_COOKIE[$cookie_name];
else { }
echo $_COOKIE[$cookie_name]; ?>
} </body>
?> </html>
</body>
</html>
Er. Simanta Kasaju 69
<?php
$cookie_name="Admin";
$cookie_value="Simanta Kasaju";
setcookie($cookie_name,$cookie_value,time()-
(86400*30),"/");
?>
<html>

<body>
<?php
echo "cookie is deleted";
?>
</body>
</html>

Er. Simanta Kasaju 70


Er. Simanta Kasaju 71
Er. Simanta Kasaju 72
Architecting Web Application
• Web application architecture defines the interactions between applications, middleware systems and
databases to ensure multiple applications can work together.
• When a user types in a URL and taps “Go,” the browser will find the Internet-facing computer the website
lives on and requests that particular page.
• The server then responds by sending files over to the browser. After that action, the browser executes
those files to show the requested page to the user. Now, the user gets to interact with the website. Of
course, all of these actions are executed within a matter of seconds. Otherwise, users wouldn’t bother
with websites.
• What’s important here is the code, which has been parsed by the browser.
• This very code may or may not have specific instructions telling the browser how to react to a wide swath
of inputs. As a result, web application architecture includes all sub-components and external applications
interchanges for an entire software application.
• Of course, it is designed to function efficiently while meeting its specific needs and goals.
• Web application architecture is critical since the majority of global network traffic, and every single app
and device uses web-based communication.
• It deals with scale, efficiency, robustness, and security.
Er. Simanta Kasaju 73
Best Practices for Good Web Application
Architecture
• You may have a working app, but it also needs to have good web architecture.
• Here are several attributes necessary for good web application architecture: Solves problems
consistently and uniformly
• Make it as simple as possible
• Supports the latest standards include Offers fast response times
• Utilizes security standards to reduce the chance of malicious penetrations
• Does not crash
• Heals itself
• Does not have a single point of failure
• Scales out easily
• Allows for easy creation of known data
• Errors logged in a user-friendly way
• Automated deployments

Er. Simanta Kasaju 74


PHP Error Handling
• Error handling is the process of catching errors raised by your program and then taking
appropriate action. If you would handle errors properly then it may lead to many unforeseen
consequences.
• Its very simple in PHP to handle an errors.
• An error message with filename, line number and a message describing the error is sent to the
browser.
• When creating scripts and web applications, error handling is an important part. If your code lacks
error checking code, your program may look very unprofessional and you may be open to security
risks.
• This tutorial contains some of the most common error checking methods in PHP.
• We will show different error handling methods:
• Simple "die()" statements
• Custom errors and error triggers
• Error reporting

Er. Simanta Kasaju 75


Basic Error Handling: Using the die() function

• The first example shows a simple script that opens a text file:
• <?php If the file does not exist you might get an
$file=fopen("[Link]","r"); error like this:
Warning: fopen([Link])
?> [[Link]]: failed to open stream:
No such file or directory
in C:\webfolder\[Link] on line 2

Er. Simanta Kasaju 76


<?php
if(file_exists("[Link]")) {
$file = fopen("[Link]", "r");
} else {
die("Error: The file does not
exist.");
}
?>

Er. Simanta Kasaju 77


Creating a Custom Error Handler

• Creating a custom error handler is quite simple. We simply create a


special function that can be called when an error occurs in PHP.
• This function must be able to handle a minimum of two parameters
(error level and error message) but can accept up to five parameters
(optionally: file, line-number, and the error context):

Er. Simanta Kasaju 78


error_function(error_level,error_message,
error_file,error_line,error_context);
Parameter Description

error_level Required. Specifies the error report level for the user-defined error. Must be a value
number. See table below for possible error report levels

error_message Required. Specifies the error message for the user-defined error

error_file Optional. Specifies the filename in which the error occurred

error_line Optional. Specifies the line number in which the error occurred

error_context Optional. Specifies an array containing every variable, and their values, in use when the
error occurred

Er. Simanta Kasaju 79


Er. Simanta Kasaju 80
Possible Error levels
These error report levels are the different types of error the user-defined error handler can be used
for. These values cab used in combination using | operator
[Link] Constant & Description Value

1 .E_ERROR 1
Fatal run-time errors. Execution of the script is halted
2 E_WARNING 2
Non-fatal run-time errors. Execution of the script is not halted
3 E_PARSE 4
Compile-time parse errors. Parse errors should only be generated by the parser.

4 E_NOTICE 8
Run-time notices. The script found something that might be an error, but could also happen when
running a script normally
5 E_CORE_ERROR 16
Fatal errors that occur during PHP's initial start-up.
6 E_CORE_WARNING 32
Non-fatal run-time errors. This occurs during PHP's initial start-up.

Er. Simanta Kasaju 81


7​ E_USER_ERROR​ 256​
Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP
function trigger_error()​
8​ E_USER_WARNING​ 512​
Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the
PHP function trigger_error()​
9​ E_USER_NOTICE​ 1024​
User-generated notice. This is like an E_NOTICE set by the programmer using the PHP
function trigger_error()​
10​ E_STRICT​ 2048​
Run-time notices. Enable to have PHP suggest changes to your code which will ensure the
best interoperability and forward compatibility of your code.
11​ E_RECOVERABLE_ERROR​ 4096​
Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see
also set_error_handler())​
12​ E_ALL​ 8191​
All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)​

Er. Simanta Kasaju 82


Error reporting

We can control which error are the displayed in script output with a build in function called error_reporting();

Eg:
<?php //only display fatal errors
error_reporting(E_ERROR);
Echo 1/0;
We can also use error_reporting() to turn off run time fatal errors.
Eg: <? Php //only display warning
Error_reporting(E_WARNING);
Echo somefunc();
It is important to realize that error_reporting doesn’t automatically make our script error free.
all it does is hide error of a certain type. We can also pass error_reporting() a combination of error levels to
customize errors. <?php
error_reporting(E_WARNING);
echo $var;// notice
echo 1/0 ;//warning
echo myfun(); //fatal
?>

Er. Simanta Kasaju 83


Now lets create a function to handle errors:
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}

Set Error Handler


The default error handler for PHP is the built in error handler. We are going to make the
function above the default error handler for the duration of the script.
It is possible to change the error handler to apply for only some errors, that way the script can
handle different errors in different ways. However, in this example we are going to use our
custom error handler for all errors: <?php
set_error_handler("customError"); //error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
Error: [8] Undefined echo($test);
variable: test ?>
Er. Simanta Kasaju 84
Trigger an Error
In a script where users can input data it is useful to trigger errors when
an illegal input occurs. In PHP, this is done by
the trigger_error() function.

Notice: Value must be 1


or below
<?php
in C:\webfolder\[Link]
$test=2;
on line 6
if ($test>=1) {
trigger_error("Val
ue must be 1 or An error can be triggered anywhere you wish in a script, and by adding a
below"); second parameter, you can specify what error level is triggered.
} Possible error types:
?> •E_USER_ERROR - Fatal user-generated run-time error. Errors that can not
be recovered from. Execution of the script is halted
•E_USER_WARNING - Non-fatal user-generated run-time warning. Execution
of the script is not halted
•E_USER_NOTICE - Default. User-generated run-time notice. The script found
something that might be an error, but could also happen when running a
script normally

Er. Simanta Kasaju 85


<?php
//error handler function
function customError($errno, $errstr) { Error: [512] Value
echo "<b>Error:</b> [$errno] $errstr<br>"; must be 1 or below
echo "Ending Script"; Ending Script
die();
}

//set error handler


set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Er. Simanta Kasaju 86
What is an Exception
• With PHP 5 came a new object oriented way of dealing with errors.
• Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This
condition is called an exception.
This is what normally happens when an exception is triggered:
• The current code state is saved
• The code execution will switch to a predefined (custom) exception handler function
• Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or
continue the script from a different location in the code
• We will show different error handling methods:
• Basic use of Exceptions
• Creating a custom exception handler
• Multiple exceptions
• Re-throwing an exception
• Setting a top level exception handler
• Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified
point.

Er. Simanta Kasaju 87


Why needs Exception Handling?
• PHP provides a powerful mechanism, exception handling. It allows
you to handle runtime errors such as IOException, SQLException,
ClassNotFoundException, and more. A most popular example of
exception handling is - divide by zero exception, which is an
arithmetic exception.

Er. Simanta Kasaju 88


example
The above error generates
because try and catch is not
<?php defined to handle the error.
//create function
with an exception Fatal error: Uncaught
function checkNum($n exception 'Exception'
umber) { with message 'Value must be 1
if($number>1) { or below' in
throw new Except C:\webfolder\[Link]
ion("Value must be 1 Stack trace: #0
or below"); C:\webfolder\[Link](12):
} checkNum(28) #1 {main} thrown
return true; in C:\webfolder\[Link] on
} line 6

//trigger exception
checkNum(2);
?>

Er. Simanta Kasaju 89


Try, throw and catch

• To avoid the error from the example above, we need to create the proper
code to handle an exception.
• Proper exception code should include:
• try - A function using an exception should be in a "try" block. If the
exception does not trigger, the code will continue as normal. However if
the exception triggers, an exception is "thrown"
• throw - This is how you trigger an exception. Each "throw" must have at
least one "catch"
• catch - A "catch" block retrieves an exception and creates an object
containing the exception information

Er. Simanta Kasaju 90


• try
• The try block contains the code that may contain an exception. An exception raised in try block during
runtime is caught by the catch block. Therefore, each try block must have at least one catch block. It
consists of the block of code in which an exception can occur.
• Following points needs to be noted about the try:
• The try block must be followed by a catch or finally block.
• A try block must have at least one catch block.
• There can be multiple catch blocks with one try block.
• catch
• The catch block catches the exception raised in the try block. It contains the code to catch the exception,
which is thrown by throw keyword in the try block. The catch block executes when a specific exception is
thrown. PHP looks for the matching catch block and assigns the exception object to a variable.
• Following points to be noted about the catch:
• There can be more than one catch block with a try.
• The thrown exception is caught and resolved by one or more catch.
• The catch block is always used with a try block. It cannot be used alone.
• It comes just after the try block.

Er. Simanta Kasaju 91


Cont..
• throw
• It is a keyword, which is used to throw an exception. Note that one throw at least
has one "catch block" to catch the exception.
• It lists the exceptions thrown by function, which cannot be handled by the
function itself.
• finally
• It is a block that contains the essential code of the program to execute. The
finally block is also used for clean-up activity in PHP. It is similar to the catch
block, which is used to handle exception. The only difference is that it always
executes whether an exception is handled or not.
• The finally block can be specified after or in place of catch block. It always
executes just after the try and catch block whether an exception has been thrown
or not, and before the normal execution restarts. It is useful in the following
scenarios - Closing of database connection, stream.
Er. Simanta Kasaju 92
<?php Example explained:
//create function with an exception The code above throws an exception and
function checkNum($number) { catches it:
if($number>1) { [Link] checkNum() function is created. It
throw new Exception("Value must be 1 or below"); checks if a number is greater than 1. If it
} is, an exception is thrown
return true; [Link] checkNum() function is called in a
} "try" block
[Link] exception within the checkNum()
//trigger exception in a "try" block function is thrown
try { [Link] "catch" block retrieves the
checkNum(2); exception and creates an object ($e)
//If the exception is thrown, this text will not be containing the exception information
shown [Link] error message from the exception
echo 'If you see this, the number is 1 or below'; is echoed by calling $e->getMessage()
} from the exception object
However, one way to get around the
//catch exception "every throw must have a catch" rule is to
catch(Exception $e) { set a top level exception handler to
echo 'Message: ' .$e->getMessage(); handle errors that slip through.
}
finally { echo '</br> It is finally block, which always executes.'; }
?> Er. Simanta Kasaju 93
<?php
class DivideByZeroException extends Exception { }
class DivideByNegativeNoException extends Exception { catch (DivideByZeroException $dze) {
} echo "Divide by Zero Exception! </br>";
function checkdivisor($dividend, $divisor){ }
// Throw exception if divisor is zero catch (DivideByNegativeNoException $dnne) {
try { echo "Divide by Negative Number Exception </
if ($divisor == 0) { br>";
throw new DivideByZeroException; }
} catch (Exception $ex) {
else if ($divisor < 0) { echo "Unknown Exception";
throw new DivideByNegativeNoException; }
} }
else {
$result = $dividend / $divisor; checkdivisor(18, 3);
echo "Result of division = $result </br>"; checkdivisor(34, -6);
} checkdivisor(27, 0);
} ?>

Er. Simanta Kasaju 94


classwork
• Write a php code for a number if it is even then throw even else
throw odd.
• Use catch for that exception
• Use any test for try

Er. Simanta Kasaju 95


//trigger an exception in a "try" block
catch (evenException $ee) {
<?php echo "even</br>";
class evenException extends Exceptio }
n { } catch (oddException $oe) {
class oddException extends Exception echo "odd </br>";
{ } }
//user- finally {
defined function with an exception echo "</br> It is finally block, which always
function test($num) { executes.<br>";
try{ }
if($num%2==0) { }
//throw an exception test(5);
throw new evenException; test(24);
} ?>
else{
throw new oddException;
}
return true;
} Er. Simanta Kasaju 96
Tag libraries
• Read yourself

Er. Simanta Kasaju 97


End of chapter 4

Er. Simanta Kasaju 98

You might also like