Unit-4 The Server Tier
Unit-4 The Server Tier
Syllabus:
The most common type of Web server which runs in the Web Hosting server is Apache,
nginx. The main purpose of web server is to store website files and broadcast them over the
internet for site visitors to see. In essence, a web server is simply a powerful computer that stores
and transmits data via the internet. When someone visits a web page on your site their browser
communicates with your web server, sending and receiving information that ultimately dictates
what appears on the visitor’s computer screen. Thus, the main purpose of a web server is to store
and transfer website data upon the request of a visitor’s browser.
5.Virtual hosting:
Virtual Hosting is a type of web hosting service in which a web server is used to host other
software based virtual web-servers web sites, data, applications and other services. Virtualized
Web servers do possess this feature to provide virtual hosting.
Dynamic Content
Dynamic content is the term used to describe site content that automatically adapts to
various predefined conditions, such as particular user signals. The content featured on the
website will adjust dynamically, or under the control of CMS(Content Management System), so
different users see different content. Dynamic content allows websites to be individually adapted
to their visitors. A site uses a variety of ways to detect significant user characteristics and
matches its content accordingly.
● It is personalizable: Every single response can be crafted based on the user’s request or
previous visits to the site.
● It is extensible: The scripting languages that power dynamic content can tap into a
variety of external resources including the local file system, databases or other servers.
● It is interactive: Dynamic websites are a two-way street, they provide content to users
and they allow users to submit information back to the server.
In-session behaviour,
User data
User-characteristics.
In-session behavior: Adapt content based on what pages they visit, which products they add to
cart, and how long they spend on site.
User data: Change content based on past purchases, customer lifecycle, or past engagements
with your marketing (engagement metrics etc).
Web servers are increasingly being used to deliver dynamic content rather than static HTML
pages. In order to generate web pages dynamically, servers need to execute a script, which
typically connects to a DBMS.
To generate dynamic contents, web servers need to execute a program, through some server-side
scripting mechanism. This script typically connects to a DBMS, performs a query, retrieves the
results and formats them in HTML in order to be returned to the user.
● First user browse web application by typing the web address into the web browser.
● Web browser send the request to web server using HTTP methods using HTTP Header.
● Web server fetch requested file/ data from server, and perform processing to get final
HTML output.
Client-side (front-end): the code that’s stored in the browser and displayed to a user. Users
interact with the client-side of the application.
Server-side (back-end): the code that application runs on the server and uses to communicate
with the hardware.
Client-side of a web application is always written with HTML, CSS, JavaScript etc. This
language is understood by browsers and allows executing fast front-end applications. For
the website server architecture, developers use general-purpose languages such as PHP, Python,
Java, Perl etc. that are understood not only by browsers but also by other hardware.
How it works?
Once a user opens a webpage, the server sends specific data to the browser as a response to the
user’s request. To be precise, a web client (or user agent) may request web resources or more
commonly-known web documents (HTML, JSON, PDF, and so on) through a web server. Then,
with these minimal manipulations, the requested information appears. After that, the interaction
between a user and a website starts.
1) Web Browser: The browser or the client-side component or the front-end component is the
key component that interacts with the user, receives the input and manages the presentation logic
while controlling user interactions with the application. User inputs are validated as well, if
required.
2) Web Server: The web server also known as the backend component or the server-side
component handles the business logic and processes the user requests by routing the requests to
the right component and managing the entire application operations. It can run and oversee
requests from a wide variety of clients.
3) Database Server: The database server provides the required data for the application. It
handles data-related tasks. In a multi-tiered architecture, database servers can manage business
logic with the help of stored procedures.
Depending on the total number of servers and databases used for a web application, the model of
a web app is decided. It can be any of the following three:
Multiple Web Servers, One Database (At a Machine Rather than the Web server):
The idea with this type of web application component model is that the webserver doesn’t store
any data. When the webserver gets information from a client, it processes the same and then
writes it to the database, which is managed outside of the server. This is sometimes also referred
to as a stateless architecture.
At least 2 web servers are required for this web application component model. This is all for
avoiding failure. Even when one of the web servers goes down, the other one will take charge.
Not more than 2 databases are required typically for the former case, while for the latter case
some data might become unavailable in the scenario of a database crash. DBMS normalization is
used, however, in both scenarios.
There are three primary types of web application architecture. Each one of them is explained as
follows:
Microservices:
These are small and lightweight services that execute a single functionality. The
Microservices Architecture framework has a number of advantages that allows developers to not
only enhance productivity but also speed up the entire deployment process. The components
making up an application build using the Microservices Architecture aren’t directly dependent on
each other. As such, they don’t necessitate to be built using the same programming language.
Serverless Architecture:
In this type of web application architecture, an application developer consults a third-party cloud
infrastructure services provider for outsourcing server as well as infrastructure management.
The benefit of this approach is that it allows applications to execute the code logic without
bothering with the infrastructure-related tasks.
The Serverless Architecture is best when the development company doesn’t want to manage or
support the servers as well as the hardware they have developed the web application for.
Introduction to PHP
PHP stands for Hypertext Pre-processor which is a server-side scripting language used to
develop static or dynamic websites or web applications. PHP uses extension “.php” and is widely
used, free and efficient. PHP code are executed on the server and the result is returned to the
browser as plain HTML. When a browser requests a document that includes PHP script, the web
server that provides the documents calls it PHP processor. The server determines that a
document includes PHP script by the file name extension “.php” or “.php3” or “.phtml”. Besides
giving out on plain HTML, PHP can output images, PDF files and even flash movies.
When a PHP processor finds only markup code (client-side scripting) in the input file then it
simply copies to the output file. When the PHP processor encounter PHP script in the input file,
it interprets it and sends any output of the script to the output file. Such output file is sent to the
requesting browser and shows output as plain HTML.
Basics of PHP:
PHP scripts are either embedded in markup documents or are in separate file referenced on
current document. PHP code can be embedded in any document by enclosing it between <?php
?>.
Syntax:
<?php
?>
This php tag can be used anywhere in a document and php file should be saved using
“.php” extension.
Step 1: local server and editor is required. We will use xampp as local server and sublime or
visual studio code as editor.
Step 2: After Xampp is downloaded start apache and mysql from xampp console.
Step 3: create a new folder on htdocs folder of xampp where your php file will resides. In my
case: I have xampp folder on C drive and I have created a new folder named unit 6 php on htdocs
folder.
Step 4: Open editor (sublime or visual studio code or brackets) and from such editor open a
folder you have just created. After opening folder, create a new file with extension “.php”. In my
case I have use visual studio code as editor and created index.php file on practice folder.
Step 5: to see output, go on web browser and type localhost/folder name/file name. In my case:
localhost/unit 6 php/xyz.php. if you have put index.php as file name then you don’t have to
mention file name. you can put localhost/folder name.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP first practice</title>
</head>
<body>
<h1> This is first heading inside HTML tag only </h1>
<?php
echo "This is php code only";
//to place html tag inside php tag we need to place such html tag inside double quote
echo "<h3> This contains html tag inside php code </h3>";
?>
</body>
</html>
Output:
While inspecting a document, only HTML script are visible but PHP code are hide by the
browser which provides security from external intrusion.
For example: for above output press ctrl+u or right click on browser and press view page source.
It will show:
In above figure, only HTML script are shown but php code is hidden.
Comments in PHP:
Comments are used to add some description of code i.e. it provides information about
code to make it more readable. Comments line are not executable statement so, any things inside
comment line are ignored by browser. It is mostly used for documenting the code. There are two
ways to add comment in php. The first way is using a pair of forward slashes i.e. “//” which
turns a whole single line into comment. The second way is using /* */ symbol which will turns
multiple line into comment. Anything between such symbol are ignore by browser. We can use
comment any where inside code.
Example:
<?php
//this is single line comment
/* this is multiple line comment
All content is ignored until “/*” symbol is placed
*/
?>
Variables in PHP:
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:
As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
After declaring a variable, it can be reused throughout the code.
Assignment Operator (=) is used to assign the value to a variable.
Rules for declaring PHP variable:
A variable must start with a dollar ($) sign, followed by the variable name.
It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
A variable name must start with a letter or underscore (_) character
A PHP variable name cannot contain spaces.
Variable name cannot start with a number or special symbols.
PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.
Syntax:
$var_name = value;
Example: variable.php
<?php
$name = "Teksan";
$age = 29;
$height = 4.5;
echo"My Name is: $name <br/> My Age is: $age <br/> My Height is: $height";
?>
Syntax:
echo “hello”; or echo(“hello”);
Print “hello”; or print(“hello”);
The two commands are quite similar but there is small difference on print and echo.
Print is a function like construct that takes a single parameter and has a return value which is
always 1 whereas echo is purely php language construct and can take multiple parameters. Echo
is faster than print because it does not have return value. Print can be used in more complex
expression as it is implemented like a function but echo cannot be used in more complex
expression.
Output:
Example: variableLocal.php
<?php
// local variables
function localvar()
{
$local = 5;
echo "This is local variable:".$local;
}
localvar();
echo "Local variable try to access from outside:".$local; // error
?>
Output:
Global variable:
The global variables are the variables that are declared outside the function. These
variables can be accessed anywhere in the program.
To access the global variable inside a function, use the GLOBAL keyword before the variable.
However, these variables can be directly accessed or used outside the function without any
keyword. Therefore there is no need to use any keyword to access a global variable outside the
function.
Example: variableGlobal.php
<?php
// global variable
$globalvar = 5;
function globvar()
{
global $globalvar;
echo "Global variable inside function: ".$globalvar."<br>";
}
globvar();
echo "Global Variable outside function: ".$globalvar;
function globalvarerror()
{
echo "Global Variable inside funaction without global keyword: ".$globalvar; // error
}
globalvarerror();
?>
Output:
Example: variableGlobal.php
<?php
// accessing global variable using GLOBALS array
$a = 5;
$b = 7;
function sum()
{
$sum = $GLOBALS['a'] + $GLOBALS['b'];
echo "Sum of a and b is:".$sum."<br>";
}
sum();
?>
Output:
Variable priority:
If two variables, local and global, have the same name, then the local variable has higher priority
than the global variable inside the function.
Example: variableGlobal.php
<?php
// variable priority
$x = 5;
function varpriority()
{
$x = 7;
echo "Value of x is: ".$x."<br>";
}
varpriority();
?>
Output:
Static variable:
Normally in PHP variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore,
another important feature of variable scoping is static variable. We use the static keyword before
the variable to define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program
execution leaves the scope. Understand it with the help of an example:
Example: variableStatic.php
<?php
function static_var()
{
static $svar = 5; // static variable
$nsvar = 10; // non-static variable
echo "Static variable before increment: ".$svar."<br>";
echo "Non-Static variable before increment: ".$nsvar."<br>";
$svar ++;
$nsvar ++;
echo "Static variable after increment: ".$svar."<br>";
echo "Non-Static variable after increment: ".$nsvar."<br>";
}
// first fuction call
echo "first function call <br>";
static_var();
// second function call
echo "<br> second function call <br>";
static_var();
?>
Output:
You have to notice that $svar regularly increments after each function call, whereas
$nsvar does not. This is why because $nsvar is not static variable, so it freed its memory and re-
initializes its value after the execution of each function call.
Function in PHP:
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and returns a
value.
Built-in functions:
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform
a specific task.
For Example: Array(), Calendar(), Date(), Time(), Error(), RegEx(), TimeZone() etc.
User-defined functions:
Besides the built-in PHP functions, it is possible to create your own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
Note that while creating a function its name should start with keyword function and all the PHP
code should be put inside { and } braces.
Example: function.php
<?php
// createing a function
function writeMessage()
{
echo "This is my first message.";
}
// calling a function
writeMessage();
?>
Example: following takes two integer parameters and add them together and then print them.
functionWihtParameter.php
<?php
$num1 = 10;
$num2 = 5;
function sum($n1, $n2)
{
$result = $n1+$n2;
echo "Sum of ".$n1." and ".$n2." is: ".$result."<br>";
}
function difference($n1,$n2)
{
$result = $n1 - $n2;
Output:
Array in PHP:
An array is a data structure that stores one or more similar type of values in a single value.
For example if you want to store 100 numbers then instead of defining 100 variables its easy to
define an array of 100 length.
Example: arrayIndex.php
<?php
// Way1
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3] <br/>";
// Way 2
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
To store the salaries of employees in an array, a numerically indexed array would not be the best
choice. Instead, we could use the employees names as the keys in our associative array, and the
value would be their respective salary.
Example: arrayAssociative.php
<?php
// Way 1
$salary=array("Sapana"=> 350000.55 ,"John"=> 450000 ,"Kartik"=> 200000);
echo "Sapana's salary:" .$salary["Sapana"]. "<br/>";
echo "John's salary: ".$salary["John"]."<br/>";
echo "Kartik's salary: ".$salary["Kartik"]."<br/>";
// Way 2
$salary["Sapana"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sapana salary: ".$salary["Sapana"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Multidimensional Arrays
In a multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example: In this example we create a two dimensional array marks to store marks of three
students in three subjects.
arrayMultidimentional.php
<?php
// crating multi-dimentional array
$marks = array(
"Rahul" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
Example: arrayForeachLoop.php
<?php
// foreach for index array
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
if(!file_exists("testfile.txt"))
{
die("file is not exist");
}
else
{
// create file
$file = fopen("testfile.txt","r");
echo "file created successfully";
}
?>
</body>
</html>
Syntax:
error_function($error_level, $error_message, $error_file, $error_line, $error_context);
This function accepts five parameters as mentioned above and described below:
● $error_level: It is required parameter and it must be an integer. There are predefined error
levels.
● $error_message: It is required parameter and it is the message which user want to print.
● $error_file: It is optional parameter and used to specify the file in which error has been
occurred.
● $error_line: It is optional parameter and used to specify the line number in which error
has been occurred.
● $error_context: It is optional parameter and used to specify an array containing every
variable and their value when error has been occurred.
set_error_handler() Function: After creating customError() function need to set custom error
handler because in normal way PHP handles it but if user doing custom error handling then user
have to set it in place of argument and pass out customError function as a string.
Example:
<?php
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
set_error_handler("customError");
$a = 10;
$b = 0;
$c = $a/$b;
echo $c;
?>
Output:
PHP Session:
An alternative way to make data accessible across the various pages of an entire website is to use
a PHP Session. PHP session is used to store and pass information from one page to another
temporarily until user close the website or destroy the session.
A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.
PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to
another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers. Session variables hold information about one single user, and are
available to all pages in one application.
<?php
session_start();
$_SESSION['user']="vijay";
echo "Session data is changed";
?>
PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends request
to the server, cookie is embedded with request. Such way, cookie can be received at the server
side.
As an example, let’s consider an application with a member area. Once a user enters their log in
details, a cookie is created on that user’s system that saves those details.
If the user comes back to the application, the login details can be automatically filled into the
form so that the user doesn’t have to repeat the process.
Cookies are also commonly used to serve advertisements based on products that the user views
around the web.
For example, if a user views a product on Amazon, they will find advertisements of similar
products when using Facebook or Google services.
Set a cookie
PHP provides us with the setcookie() function to create, or set, a cookie.
Syntax:
setcookie(name, value, expire, path, domain, security);
The first argument, name, is mandatory for every cookie. The rest of the arguments are optional,
but recommended.
Argument Usage
Name Required. The name the cookie will be referred to. Must be a
string.
Value Optional. The value of the cookie.
Expire Optional. If an expiration time is not set, the cookie will expire
when the browser is closed.
Path Optional. The path on the server the cookie will be available on.
The cookie can be set to '/' to be available to the entire domain.
Domain Optional. The (sub) domain that the cookie is available to. Sub-
domains of the specified domain are automatically included.
Security Optional. If set to true (1), the cookie will only be set for a
HTTPS secure connection.
Example:
<?php
$cookiename = "user";
$cookievalue = "Gopal";
// Expires when the browser closes
setcookie("$cookiename","$cookievalue");
echo "cookie is set successfully";
For accessing a cookie value, the php $_COOKIE superglobal variable is used. It is an
associative array that contains a record of all the cookies values sent by the browser in the
current request. The records are stored as a list where the cookie name is used as the key.
To access a cookie named “user”, the following code can be executed.
Example:
<?php
echo $_COOKIE['user'];
?>
Deleting Cookies:
The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie()
function is called by passing the cookie name and other arguments or empty strings but however
this time, the expiration date is required to be set in the past or time in negative value.
Example: To delete a cookie named “user”, the following code can be executed.
<?php
setcookie("user","",time()-60);
echo "cookie is deleted successfully";
?>
This (-60) means it will delete all the cookies named “user” set 1minute before. If we set (-3600)
it means all cookies set before 1 hour will be deleted.
Important Points:
If the expiration time of the cookie is set to 0 or omitted, the cookie will expire at the end
of the session i.e. when the browser closes.
The same path, domain, and other arguments should be passed that were used to create
the cookie in order to ensure that the correct cookie is deleted.
Difference between Storing Data in Cookies and Session Variable:
Cookies are returned and stored in the user’s browser, session data is stored in web
server.
The life span of cookie can be set to almost any duration of our choice. Php session have
a predefined short life (when the browser is closed).
Depending on how web server is configured session data is often stored in public
temporary directory on the server. As such it is possible that other users on the server
may be able to peek at the data stored in server.
storing information in session variable. For e.g. do not store credit card number, person
particulars, passwords, username etc. in session variable.
End of Uni-4