0% found this document useful (0 votes)
38 views33 pages

Unit-4 The Server Tier

The document covers the concept of web servers, their applications, and the generation of dynamic content in web technology for BCA 3rd semester. It explains the architecture of web applications, including client-side and server-side components, and discusses different models and types of web application architecture. Additionally, it introduces PHP as a server-side scripting language, detailing its syntax, integration with HTML, and basic programming concepts.

Uploaded by

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

Unit-4 The Server Tier

The document covers the concept of web servers, their applications, and the generation of dynamic content in web technology for BCA 3rd semester. It explains the architecture of web applications, including client-side and server-side components, and discusses different models and types of web application architecture. Additionally, it introduces PHP as a server-side scripting language, detailing its syntax, integration with HTML, and basic programming concepts.

Uploaded by

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

Web Technology – BCA 3rd Semester

Unit-4: The Server Tier

Syllabus:

The Web Server Concept:


Web server is basically a software program which handles the requests made from the
Internet user. Web server takes care of your request for locating the host of the Web address.
Web server software located in the server of the web hosting does on getting the request can be
described as follows:

- It accepts the request made.


- Check the request
- Estimate what additional applications need to run to access the files requested
- Completes the task
- Sends back the answer (response) to your computer

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.

Application of Web Server:

1.Stores and secures website data:


In web hosting services, a web server stores all website data and secures it from
unauthorized users when it is properly configured.

2.Provides web database access:


A web server’s responsibility is to provide access to websites that are hosted. Web hosting
service providers own some web servers that are used in variable ways to provide different web
hosting services, such as backend database servers.

Teksan Gharti, Page 1


Web Technology – BCA 3rd Semester

3.Serve the end user requests:


Web servers accept requests from different users connected over the internet and serve
them accordingly.

4.Bandwidth controlling to regulate network traffic:


It is a feature available in web server to minimize excess network traffic. Web Hosts can set
bandwidth values to regulate the rate of data transmission over the internet. This feature avoids
the down time caused by high web traffic.

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.

6.Server side web scripting:


This feature of web server enables the user to create dynamic web pages. The popular server side
scripting languages include Perl, Ruby, Python, PHP, ASP, etc.

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.

Advantages of Dynamic Content:


Unlike static content, dynamic content can respond to the individual needs of the current user. So
it can be more useful, interesting and entertaining for website visitors than static content
displayed in the same way to each and every user. The major benefits are as follows:

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

Teksan Gharti, Page 2


Web Technology – BCA 3rd Semester

● It is seamless (smooth without interrupt): By combining server-side scripts with scripts


that run in the browser, websites can load dynamic content over an already-loaded web
page without the user being aware of it.

Creating Dynamic Content:


Dynamic content is a web page or email component that changes. Typically, changes are
based on user signals that include

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

User characteristics: Adapt content based on demographics such as geo-location or buyer


personas.

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.

Fig: Dynamic Content Generation Process

Teksan Gharti, Page 3


Web Technology – BCA 3rd Semester

Process how dynamic content generation code works:

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

● After processing server send HTML code back to web browser.

Web Application Architecture:


Web application architecture describes the relationships between databases, servers, and
applications in a system. It determines how the functionality and logic of a system are distributed
between server-side and client-side. Basically, architecture is responsible for fitting together all
the application elements: what your users see and interact with, and how the software handles
operations on the internal level.

All web applications are made up of two basic components

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.

So, what’s web application architecture?


Briefly, the web application architecture is a “skeleton” or layout that displays the
interactions between application components, middleware systems, user interfaces, and
databases. This kind of interaction allows a number of applications to work together
simultaneously.

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.

Teksan Gharti, Page 4


Web Technology – BCA 3rd Semester

Web application architecture components:


Typically web-based application architecture comprises 3 core components:

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.

Teksan Gharti, Page 5


Web Technology – BCA 3rd Semester

Models of Web Application Components:

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:

 One Web Server, One Database


 Multiple Web Servers, One Database
 Multiple Web Servers, Multiple Databases

One Web Server, One Database:


It is the most simple as well as the least reliable web app component model. Such a model uses a
single server as well as a single database. A web app builds on such a model will go down as
soon as the server goes down. Hence, it isn’t much reliable.

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.

Multiple Web Server, Multiple Databases:


It is the most efficient web application component model because neither the webservers nor the
databases have a single point of failure. There are two options for this type of model. Either to
store identical data in all the employed databases or distribute it evenly among them.

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.

Types of Web Application Architecture:

A web application architecture is a pattern of interaction between various web application


components. The type of web application architecture depends on how the application logic is
distributed among the client and server sides.

There are three primary types of web application architecture. Each one of them is explained as
follows:

Teksan Gharti, Page 6


Web Technology – BCA 3rd Semester

Single-Page Applications (SPAs):


Instead of loading completely new pages from the server each time for a user action,
single page web applications allows for a dynamic interaction by means of providing updated
content to the current page. AJAX, a concise form of Asynchronous JavaScript and XML, is the
foundation for enabling page communications and hence, making SPAs a reality. SPAs are
designed in a way so that they request for most necessary content and information elements. This
leads to the procurement of an intuitive as well as interactive user experience.

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.

Teksan Gharti, Page 7


Web Technology – BCA 3rd Semester

PHP with MySql in Web Development:

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:

Syntax for Using 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

// necessary php code

?>

This php tag can be used anywhere in a document and php file should be saved using
“.php” extension.

Teksan Gharti, Page 8


Web Technology – BCA 3rd Semester

Steps for Running PHP File:

Step 1: local server and editor is required. We will use xampp as local server and sublime or
visual studio code as editor.

Download xampp: https://www.apachefriends.org/download.html

Download visual studio code: https://code.visualstudio.com/download

Download sublime text: https://www.sublimetext.com/3

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.

Teksan Gharti, Page 9


Web Technology – BCA 3rd Semester

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.

Teksan Gharti, Page 10


Web Technology – BCA 3rd Semester

Combining PHP and HTML:


PHP syntax is applicable only within PHP tags. PHP can be embedded in HTML and
placed anywhere in the document. When PHP is embedded in HTML documents and PHP parses
this document it interpreted the section enclosed with an opening tag (<?php) and closing tag (?
>) of PHP and ignore the rest parts of the document.

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:

Teksan Gharti, Page 11


Web Technology – BCA 3rd Semester

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

Teksan Gharti, Page 12


Web Technology – BCA 3rd Semester

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

PHP Echo and Print Command:


Both echo and print are used to produce output to the screen and both the statement can
be used with or without parenthesis.

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.

Teksan Gharti, Page 13


Web Technology – BCA 3rd Semester

Example on Difference Between Echo and Print:

Teksan Gharti, Page 14


Web Technology – BCA 3rd Semester

Output:

PHP Variable Scope


The scope of a variable is defined as its range in the program under which it can be
accessed. In other words, "The scope of a variable is the portion of the program within which it
is defined and can be accessed."
PHP has three types of variable scopes:
 Local variable
 Global variable
 Static variable
Local variable:
The variables that are declared within a function are called local variables for that function.
These local variables have their scope only in that particular function in which they are declared.
This means that these variables cannot be accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely different from the
variable declared inside the function.

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

Teksan Gharti, Page 15


Web Technology – BCA 3rd Semester

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:

Teksan Gharti, Page 16


Web Technology – BCA 3rd Semester

Using $GLOBALS instead of global


Another way to use the global variable inside the function is predefined $GLOBALS array.

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:

Teksan Gharti, Page 17


Web Technology – BCA 3rd Semester

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:

Teksan Gharti, Page 18


Web Technology – BCA 3rd Semester

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.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times, like in
other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the
use of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application because every logic is divided in the form of functions.
There two types of functions
 Built-in Function
 User-defined Function

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.

Teksan Gharti, Page 19


Web Technology – BCA 3rd Semester

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.

Creating and Calling PHP Function


It’s very easy to create your own PHP function. Suppose you want to create a PHP function
which will simply write a simple message on your browser when you will call it. Following
example creates a function called writeMessage() and then calls it just after creating it.

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

PHP Functions with Parameters


PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function.

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;

Teksan Gharti, Page 20


Web Technology – BCA 3rd Semester

echo "Difference between ".$n1." and ".$n2. " is: ".$result;


}
sum(5,6); // passing values directly
difference($num1,$num2); // passing values using variable
?>

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.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and object
in the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:
Way 1:
$arrayName = array(“value1”, “value2”, “value3”, “valueN”);
Way 2:
$arrayName[0] = “Value1”;
$arrayName[1] = “Value2”;
$arrayName[2] = “Value3”;
$arrayName[3] = “ValueN”;

Teksan Gharti, Page 21


Web Technology – BCA 3rd Semester

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]";
?>

PHP Associative Arrays


The associative arrays are very similar to numeric arrays in term of functionality but
they are different in terms of their index. Associative array will have their index as string so that
you can establish a strong association between key and values. We can associate name with each
array elements in PHP using => symbol.

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/>";
?>

Teksan Gharti, Page 22


Web Technology – BCA 3rd Semester

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

"Sangita" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"Sunidhi" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

//Accessing multi-dimensional array values


echo "Marks for Rahul in physics : ".$marks['Rahul']['physics']. "<br />";
echo "Marks for Sangital in maths : ".$marks['Sangita']['maths']. "<br />";
echo "Marks for Sunidhi in chemistry : ".$marks['Sunidhi']['chemistry']. "<br />";
?>

Teksan Gharti, Page 23


Web Technology – BCA 3rd Semester

PHP foreach loop


The foreach loop is used to traverse the array elements. It works only on array and object. It will
issue an error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate
the elements of an array. In foreach loop, we don't need to increment the value.

Example: arrayForeachLoop.php

<?php
// foreach for index array
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}

// foreach for associate array


$age = array("Rahul" => "35", "Sangita" => "37", "Sunidhi" => "43");
foreach($age as $name => $marks)
{
echo "$name = $marks <br>";
}
?>

Error Handling in PHP:


PHP is used for web development. Error handling in PHP is almost similar to error
handling in all programming languages. The default error handling in PHP will give file name
line number and error type.

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.

Ways to handle PHP Errors:


● Using die() method
● Custom Error Handling

Using die() function


The die() function print a message and exit from current script.
Syntax:
die( $message );

Teksan Gharti, Page 24


Web Technology – BCA 3rd Semester

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

Custom Error Handling:


Creating a custom error handler in PHP is quite simple. Create a function that can be called
when an error has been occurred in PHP.

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.

Teksan Gharti, Page 25


Web Technology – BCA 3rd Semester

Error Report levels


These error report levels are the different types of error the user-defined error handler can be
used for:
● 1 : E_ERROR :fatal runtime error execution of script has been halted
● 2 : E_WARNING :non fatal runtime error execution of script has been halted
● 4 : E_PARSE :compile time error it is generated by the parser
● 8 :E_NOTICE :The script found something that might be an error
● 16 :E_CORE_ERROR :Fatal errors that occurred during initial startup of script
● 32 :E_CORE_WARNING :Non fatal errors that occurred during initial startup of script
● 8191 :E_ALL :All errors and warning

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:

Teksan Gharti, Page 26


Web Technology – BCA 3rd Semester

PHP State Management (Session and Cookies):


The basic foundation of a data communication system for the internet is HTTP
(Hypertext Transfer Protocol) which is an application layer protocol, distributive and
collaborative, and hypermedia information system. As we know that HTTP is a generic and
stateless protocol to manage state in applications like E-commerce, Social Media, Blog sites,
many commercial sites sessions and cookies are used.

Type of state management system


Server-side state management system: In server-side state management system where we used
to store user specific information to identify user on server and information is available in every
web pages.
Example: session variables
Client side State management System: In a client-side state management system, the user
information is stored by the browser.
Example: cookies

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.

Start a PHP Session


A session is started with the session_start() function. Session variables are set with the PHP
global variable: $_SESSION.
Now, let's create a new page called "sessionStart.php". In this page, we start a new PHP session
and set some session variables:
sessionStart.php
<?php
session_start();
echo "Session Started <br>";
//set session variable
$_SESSION['user'] = "teksan";
echo "Session variable is set";
?>

Teksan Gharti, Page 27


Web Technology – BCA 3rd Semester

Get PHP Session Data


Next, we create another page called "sessionVariableDisplay.php". From this page, we will
access the session information we set on the first page ("sessionStart.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page by using session_start()
function.
Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
session_start();
echo"User Name is: ".$_SESSION['user'];
?>

Change session data


Session variables are mutable, which means they can be changed during runtime. To change the
value of a session variable, we simply assign a new value to it.

<?php
session_start();
$_SESSION['user']="vijay";
echo "Session data is changed";
?>

Destroy a PHP Session


To remove all global session variables and destroy the session,
use session_unset() and session_destroy() functions.
<?php
session_start();
session_unset();
session_destroy();
echo "Session is Destroyed";
?>

Teksan Gharti, Page 28


Web Technology – BCA 3rd Semester

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.

In short, cookie can be created, sent and received at server end.


Cookies are states that are saved to the user’s system, instead of the server. Unlike a session, a
cookie has a 1024 byte size limit. Cookies are sent to the web server as header information in
every HTTP request.
NOTE: Cookies are not stored on the server, they can be modified and deleted. Cookies are less
reliable and secure than sessions.

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.

Teksan Gharti, Page 29


Web Technology – BCA 3rd Semester

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

// Expires in 1 minute (60 seconds)


setcookie("$cookiename", "$cookievalue", time()+60);
echo "Cookie set";

// Only available to a specific subdomain over HTTPS parameter 1 means true


setcookie("$cookiename", "$cookievalue", time()+60, "/mypath/", "mydomain.com", 1);
echo "cookie is set";
?>

Accessing Cookie Values:


Teksan Gharti, Page 30
Web Technology – BCA 3rd Semester

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'];
?>

Modify Cookie values:


To modify a cookie, just set (again) the cookie using the setcookie() function:
Example:
<?php
$cookiename = "user";
$cookievalue = "Rohan";
setcookie("user","Rohan",time()+60);
echo "cookie is Modify successfully";
?>

Checking Whether a Cookie Is Set Or Not:


It is always advisable to check whether a cookie is set or not before accessing its value.
Therefore to check whether a cookie is set or not, the PHP isset() function is used.
Example: To check whether a cookie “user” is set or not, the isset() function is executed as
follows:
<?php
if(isset($_COOKIE['user']))
{
echo $_COOKIE['user'];
}
else
{
echo "Cookie is not set";
}
?>

Deleting Cookies:

Teksan Gharti, Page 31


Web Technology – BCA 3rd Semester

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.

When to Use Session Rather than Cookies:


When we need the data stored on the server and not in user’s browser:
When a cookie is set, it is return to the user and stored in browser. Sometimes this is not a good
idea.
For example: some website have a CAPTCHA test on their web comment forms where an image
showing a few random letters and numbers is displayed and users are supposed to type in those
characters to prove that they are human and not some spam. In order for this to work the script
generating the image needs to be stored in secret word somewhere so that the program doing the
checking can verify the user’s answer.
In such case returning a cookie to the user is not good since a span on receiving that cookie can
find out the secret word. We can encrypt it but why bother when PHP session is exactly what we
need for this purpose.
When the data is transient, and only relevant for the current browsing session:
Since we don’t know how long session data will be stored it stands to reason that we should only
use session when we don’t really need data for long periods of time and when the data is not so
important.
When the data does not contain any information that needs to be securely kept:
As session data is kept in temporary directory on web server, this is usually a public accessible
folder that anyone with an account on the computer can read. So we should be careful while

Teksan Gharti, Page 32


Web Technology – BCA 3rd Semester

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

Teksan Gharti, Page 33

You might also like