It3401 LN
It3401 LN
Internet
Advantages
Internet covers almost every aspect of life, one can think of. Here, we will discuss
some of the advantages of Internet:
Disadvantages
However, Internet has prooved to be a powerful source of information in almost
every field, yet there exists many disadvanatges discussed below:
There are always chances to loose personal information such as name,
address, credit card number. Therefore, one should be very careful while
sharing such information. One should use credit cards only through
authenticated sites.
Another disadvantage is the Spamming.Spamming corresponds to the
unwanted e-mails in bulk. These e-mails serve no purpose and lead to
obstruction of entire system.
Virus can easily be spread to the computers connected to internet. Such virus
attacks may cause your system to crash or your important data may get
deleted.
Also a biggest threat on internet is pornography. There are many
pornographic sites that can be found, letting your children to use internet
which indirectly affects the children healthy mental life.
There are various websites that do not provide the authenticated information.
This leads to misconception among many people.
This tutorial will discover the definition of computer networking, its types, computer
networks work, networking concepts, commonly used terms, networking and
internet, how it works, and network topologies.
Computer Network
"A Computer Network is defined as a set of two or more computers that are linked
together?either via wired cables or wireless networks i.e., WiFi?with the purpose of
communicating, exchanging, sharing or distributing data, files and resources."
Though one can also define the computer networks based on their geographic
location, a LAN (local area network) connects computers in a definite physical
dimension, such as home or within an office.
One can also describe the concept of computer networking by its communicating
protocols, the physical arrangement of its networking elements, how it manages
network traffic, and it's functioning.
All the other technologies, including the internet, Google search, instant
messaging apps, online video streaming, social media, email, cloud kitchen,
cloud data storage, etc., all exist because of computer networks.
LAN or Local Area Network is a group of devices connecting the computers and
other devices such as switches, servers, printers, etc., over a short distance such as
office, home. The commonly used LAN is Ethernet LAN. This network is used as it
allows the user to transfer or share data, files, and resources.
2. MAN
MAN or Metropolitan Area Network is typically a more extensive network when
compared to LANs but is smaller than WANs. This network ranges between several
buildings in the same city. Man networks are connected via fiber optic cable (usually
high-speed connection). Cities and government bodies usually manage MANs.
3.WAN
WAN or Wide Area Network is the most significant network type connecting
computers over a wide geographical area, such as a country, continent. WAN
includes several LANs, MANs, and CANs. An example of WAN is
the Internet, which connects billions of computers globally.
1. IP address
An IP address or Internet Protocol is a unique number that represents the
address where you live on the Internet. Every device that is connected to the
network has a string of numbers or IP addresses unlike house addresses.
You won't find two devices connected to a network with an identical IP address.
When your computer sends data to another different, the sent data contains a
'header' that further contains the devices' IP address, i.e., the source computer and
the destination device.
2. Nodes
A node refers to a networking connection point where a connection occurs inside
a network that further helps in receiving, transmitting, creating, or storing files
or data.
3. Routers
A router is a physical networking device, which forwards data packets between
networks. Routers do the data analysis, perform the traffic directing functions on
the network, and define the top route for the data packets to reach their destination
node. A data packet may have to surpass multiple routers present within the
network until it reaches its destination.
4. Switches
In a computer network, a switch is a device that connects other devices and helps
in node-to-node communication by deciding the best way of transmitting data
within a network (usually if there are multiple routes in a more extensive
network).
o Circuit Switching
o Packet Switching
o Message Switching
5. Ports
A port allows the user to access multiple applications by identifying a
connection between network devices. Each port is allocated a set of string
numbers. If you relate the IP address to a hotel's address, you can refer to ports as
the hotel room number. Network devices use port numbers to decide which
application, service, or method is used to forward the detailed information or the
data.
Internet is a giant hub of information, but this information is not sent to every
computer connected to the Internet. The protocols and infrastructure are responsible
for managing to share the precise information the user has requested.
Network Topology
"Network topology is defined as the arrangement of computers or nodes of a
computer network to establish communication among all."
A node refers to a device that can transmit, receive, create, or store information. The
nodes are connected via a network link that could be either wired (cables, Ethernet)
or wireless (Bluetooth, Wi-Fi).
2. Ring Topology
o A Ring topology is a modified version of bus topology where every node is
connected in a closed-loop forming peer-to-peer LAN topology.
o Every node in a ring topology has precisely two connections. The Adjacent
node pairs are connected directly, whereas the non-adjacent nodes are
indirectly connected via various nodes.
o Ring topology supports a unidirectional communication pattern where
sending and receiving of data occurs via TOKEN.
3. Star Topology
, there are vast numbers of users' communicating with different devices in different
languages. That also includes many ways in which they transmit data along with the
different software they implement. So, communicating worldwide will not be
possible if there were no fixed 'standards' that will govern the way user
communicates for data as well as the way our devices treat those data. Here we will
be discussing these standard set of rules.
Yes, we're talking about "protocols" which are set of rules that help in governing the
way a particular technology will function for communication. In other words, it can
be said that the protocols are digital languages implemented in the form of
networking algorithms. There are different networks and network protocols, user's
use while surfing.
Types of Protocols
There are various types of protocols that support a major and compassionate role in
communicating with different devices across the network. These are:
Web Essentials:
Server:
The software that distributes the information and the machine where the
information and software reside is called the server.
Client:
The software that resides on the remote machine, communicates with the
server, fetches the information, processes it, and then displays it on the remote
machine is called the client.
Web server:
Software that delivers Web pages and other documents to browsers using the
HTTP protocol
Web Page:
Website:
A collection of pages on the World Wide Web that are accessible from the
same URL and typically residing on the same server.
URL:
Uniform Resource Locator, the unique address which identifies a resource on the
Internet for routing purposes.
Client-server paradigm:
Web Browsers:
o Firefox
Web Server:
Protocol:
Internet Protocol:
There are many protocols used by the Internet and the WWW:
o TCP/IP
o HTTP
o FTP
TCP/IP
The Internet uses two main protocols (developed by Vincent Cerf and Robert Kahn)
Transmission control protocol (TCP):Controls disassembly of message into
packets at the origin reassembles at the destination
Internet protocol (IP):Specifies the addressing details for each packet Each
packet is labelled with its origin and destination.
Hypertext Transfer Protocol (HTTP)
o e.g. can send specific messages to the client rather than all the
messages. A user can view email message headers and the
sender’s name before
The disadvantage of POP: You can only access messages from one PC.
The disadvantage of IMAP :Since email is stored on the email server, there is a
need for more and more expensive (high speed) storage space.
World Wide Web: comprises software (Web server and browser) and data
(Web sites).
HTTP:
Hypertext Transfer Protocol (HTTP) is the communication protocol
used by the Internet to transfer hypertext documents.
other text that the reader can immediately follow, usually by a mouse HTTP is
behind every request for a web document or graph, every click of a hypertext link,
and every submission of a form.
HTTP specifies how clients request data, and how servers respond to
these requests.
The client makes a request for a given page and the server is
responsible for finding it and returning it to the client.
HTTP Transactions
HTTP Message:
HTTP message is the information transaction between the client and server.
1. Requests
a. Client to server
2. Responses
a. Server to client
Fields
· Request line or Response line
· General header
· Request header or Response header
· Entity header
· Entity body
Request Message:
Request Line:
o The path is the part of the URL after the host name, also called
the request URI o The HTTP version always takes the form
"HTTP/x.x", uppercase.
Request Header:
Response Message:
Response Line:
HTTP Method:
• HTTP method is supplied in the request line and specifies the operation
that the client has requested.
• For example, displaying the balance of a bank account has no effect on the
account and can be safely repeated.
• Most browsers will allow a user to refresh a page that resulted from a GET,
without displaying any kind of warning
• GET requests is that they can only supply data in the form of parameters
encoded in the URI (known as a Query String) – [downside]
Cannot be unused for uploading files or other operations that require large amounts
of data to be sent to the server.
• Used for operations that have side effects and cannot be safely repeated.
• For example, transferring money from one bank account to another has
side effects and should not be repeated without explicit approval by the user.
If you try to refresh a page in Internet Explorer that resulted from a POST, it
displays the following message to warn you that there may be side effects:
• The IIS server returns two status codes in its response for a POST request
o The first is 100 Continue to indicate that it has successfully
received the POST
request
o The second is 200 OK after the request has been processed.
• Informational (1xx)
• Successful (2xx)
• Redirection (3xx)
o 301: moved permanently
• Client error (4xx)
o 403 :
forbidden o
404: Not
found
• Server error (5xx)
o 503: Service unavailable
o 505: HTTP version not supported
5. Describe client side scripting?
Client side scripting is a process in which the code along with HTML web
page is sent to the client by the server. Here, the code refers to the script.
In other simple words, client side scripting is a process in which scripts are
executed by browsers without connecting the server.
The code executes on the browser of client’s computer either during the
loading of web page or after the web page has been loaded.
Client side scripting is mainly used for dynamic user interface elements,
such as pull-down menus, navigation tools, animation buttons, data
validation purpose, etc.
Today, it is rapidly growing and evolving day by day. As a result, writing
client side web programming is now easier and faster, thereby, reducing
load on the server.
JavaScript and jQuery are by far the most important client-side scripting
languages or web scripting languages and widely used to create a
dynamic and responsive webpage and websites.
The browser (temporarily) downloads the code in the local computer and
starts processing it without the server. Therefore, the client side scripting is
browser dependent.
Client side scripts may also have some instructions for the web browser to
follow in response to certain user actions, such as pressing a page button.
They can often be looked if client want to view the source code of web
page.
<html>
<head>
<title>List of cities</title>
<script>
function displayCities()
{
var cities = ["New York", "Dhanbad", "Paris", "London", "Mumbai"];
listItem.appendChild(document.createTextNode(cities[city]));
</script>
</head>
<ul id = "cityList"></ul>
</body>
</html>
Look at the below diagram that shows the flow of data between server and
browser.
Application of Client side Scripting
Client side scripting is used to make web pages or website more interactive.
It is primarily used at the frontend, where the user can see using the
browser. Some important applications of client side scripting are listed, as
below:
To retrieve data from web browser or user’s screen.
Used in the field of online games.
To customize the web page without reloading the page.
Client side scripting is used for validation purpose. If the user enters
incorrect credentials on the login page, the web page displays an
error message on the client machine without submitting it to the web
server.
To create ad banners that interact with the user, rather than simply
displaying graphics.
To create animated images that change when we move the mouse
over them.
Client side script can be used to detect installed plug-ins and notify
the user if a plugin is required.
<script>Malicious code</script>
If JavaScript is enabled on the victim client’s browser, the browser will run
this code unexpectedly.
3. An attacker can send a file to a client and encourage him to post it to the
server. The file may contain malicious code that can hack the website.
4. When a client visits a website, a small text file called a cookie is often
placed in the client’s computer. At the next visiting, the web server scans
that cookie. If it found on the computer, the attacker can use the cookie
data to trigger the download of malicious code.
5. Tags like <FORM> can trouble if they are inserted at the wrong place.
These HTML tags can change the appearance of the web page.
6. Browsers interpret the information according to the character set chosen
by the client. If the client does not specify the character set, the web
browser uses the default setting, that can display the garbled appearing or
unintended meanings.
• HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this is a
link", etc.
Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
Example explanation:
• The <!DOCTYPE html> declaration defines that this document is an HTML5 document
• The <head> element contains meta information about the HTML page
• The <title> element specifies a title for the HTML page (which is shown in the browser's title bar
or in the page's tab)
• The <body> element defines the document's body, and is a container for all the visible contents,
such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
HTML Element
An HTML element is defined by a start tag, some content, and an end tag:
The HTML element is everything from the start tag to the end tag:
Web Browsers
The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents and display
them correctly.
A browser does not display the HTML tags, but uses them to determine how to display the document:
HTML Page Structure
2. Define form tag. Design a registration page by using all form controls?
The form is basically used for the registration process, logging into your profile on a website or to
create your profile on a website, etc … The information that is collected from the form is -1. Name 2.Email
Addresses etc. Now the form will take input from the form and post that data in backend applications (like
PHP). So the backend application will process the data which is received by them. There are various form
elements that we can use like text fields, text area, drop-down list, select, checkboxes, radio, etc.
Syntax:
Registration page
Example:
<form>
<div class="container">
<h1>Register Here</h1>
<hr>
<label for="pwd"><b>Password</b></label>
<hr>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
</div>
<div class="container signin">
</div>
</form>
Output:
With CSS, you can control the color, font, the size of text, the spacing between elements, how elements
are positioned and laid out, what background images or background colors are to be used, different
displays for different devices and screen sizes, and much more!
CSS Example
<style>
</style>
CSS Syntax
The declaration block (in curly braces) contains one or more declarations separated by
semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
In the following example all <p> elements will be center-aligned, red and have a font size of 32
pixels:
Example
<style>
p {font-size:32px; color:red; text-align:center;}
</style>
<style>
p{
font-size: 32px;
color: red;
text-align: center;
}
</style>
CSS Background
CSS background property is used to define the background effects on element. There are 5 CSS
background properties that affects the HTML elements:
1. background-color
2. background-image
3. background-repeat
4. background-attachment
5. background-position
1) CSS background-color
The background-color property is used to specify the background color of the element.
2) CSS background-image
By default, the background-image property repeats the background image horizontally and
vertically. Some images are repeated only horizontally or vertically.
4) CSS background-attachment
The background-position property is used to define the initial position of the background
image. By default, the background image is placed on the top-left of the webpage.
1. center
2. top
3. bottom
4. left
5. right
4. How to create CSS animation and briefly explain about user interface.?
CSS animation:
Animation is a way using which we can create the illusion of motion by placing still images one
after another in a typical format. For example, we can have a ball rising up at some instant than
falling down as an animation effect. CSS provides us some properties to control the animation
effect by changing some of its variables like timing and key frames etc.
• @keyframes
• animation-name
• animation-duration
• animation-delay
• animation-iteration-count
• animation-direction
• animation-timing-function
• animation-fill-mode
• animation
The @keyframes
When you specify CSS styles inside the @keyframes rule, the animation will gradually change
from the current style to the new style at certain times.
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
Animation-duration
The animation-duration property defines how long an animation should take to complete.
If the animation-duration property is not specified, no animation will occur, because the default
value is 0s
Delay an Animation
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-delay: 2s;
}
Animation-iteration-count:
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: 3;
}
Animation-direction:
• ease - Specifies an animation with a slow start, then fast, then end slowly (this is default)
• linear - Specifies an animation with the same speed from start to end
CSS animations do not affect an element before the first keyframe is played or after the last
keyframe is played. The animation-fill-mode property can override this behavior.
The animation-fill-mode property specifies a style for the target element when the animation is
not playing (before it starts, after it ends, or both).
• none - Default value. Animation will not apply any styles to the element before or after it
is executing
• forwards - The element will retain the style values that is set by the last keyframe
(depends on animation-direction and animation-iteration-count)
• backwards - The element will get the style values that is set by the first keyframe
(depends on animation-direction), and retain this during the animation-delay period
• both - The animation will follow the rules for both forwards and backwards, extending
the animation properties in both directions
User interface:
User Interface (UI) defines the way humans interact with the information systems. In Layman’s
term, User Interface (UI) is a series of pages, screens, buttons, forms and other visual elements
that are used to interact with the device. Every app and every website has a user interface.
The user interface property is used to change any element into one of several standard user
interface elements.
• resize
• outline-offset
Resize Property: The resize property is used to resize a box by user. This property does not
apply to inline elements or block elements where overflow is visible. In this property, overflow
must be set to “scroll”, “auto”, or “hidden”.
Syntax:
resize: horizontal,vertical,both;
Syntax:
resize: horizontal;
Supported Browsers: The browser supported by resize property are listed below:
• Opera 15.0
outline-offset: The outline-offset property in CSS is used to set the amount of space between an outline
and the edge or border of an element. The space between the element and its outline is transparent.
Syntax:
outline-offset: length;
Supported Browsers: The browser supported by outline-offset property are listed below:
• Firefox 3.5
• Opera 10.5
Introduction to JavaScript
Part-b
JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is
dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any
type of values such as numbers, strings etc. For example:
There are five types of primitive data types in JavaScript. They are as follows:
Variable:
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript :
local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
1. var x = 10;
2. var _value="sonoo";
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
30
A JavaScript local variable is declared inside block or function. It is accessible within the function or block
only. For example:
<script>
function abc(){
</script>
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function
or declared with window object is known as global variable. For example:
<script>
function a(){
document.writeln(data);
function b(){
document.writeln(data);
b();
</script>
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:
var sum=10+20;
1. Arithmetic Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The following operators
are known as JavaScript arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
Operator precedence:
Operator precedence describes the order in which operations are performed in an arithmetic expression.
Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).
Math Object
Math Properties
PI Returns Π value.
Math Methods
Methods Description
<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">
var value = Math.abs(20);
document.write("ABS Test Value : " + value +"<br>");
Output
2. Date Object
• Date object allows you to get and set the year, month, day, hour, minute, second and
millisecond fields.
Syntax:
var variable_name = new Date();
Example:
var current_date = new Date();
Date Methods
Methods Description
getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.
setMonth() Sets the month.
<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html>
Output:
4. Write a JavaScript code for validating new user registration form which includes the fields like
username, password, confirm password, gender, date of birth, contact number and mail id.
<!DOCTYPE html>
<html>
<head>
<title>Reg Form</title>
<style type="text/css">
body{
font-family: Calibri;
input[type="text"] {
width: 250px;
input[type="submit"], input[type="reset"] {
width: 77px;
height: 27px;
form{
text-align: center;
font-family: Calibri;
font-size: 20px;
width: 600px;
}
td {
padding: 10px;
td:first-child {
text-align: right;
font-weight: bold;
td:last-child {
text-align: left;
</style>
<script>
function validate() {
if (fname.value.length <= 0) {
alert("Name is required");
fname.focus();
return false;
if (lname.value.length <= 0) {
alert("Last Name is required");
lname.focus();
return false;
if (address.value.length <= 0) {
alert("Address is required");
address.focus();
return false;
if (gender.value.length <= 0) {
alert("Gender is required");
gender.focus();
return false;
if (email.value.length <= 0) {
alert("Email Id is required");
email.focus();
return false;
if (mobile.value.length <= 0) {
mobile.focus();
return false;
alert("Course is required");
course.focus();
return false;
return false;
</script>
</head>
<body>
<hr>
<h2>Registration Form</h2>
<table>
<tr>
<td>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td><label>Address: </label></td>
<td>
<input type="textarea" size="50" name="address" placeholder="Address">
</td>
</tr>
<tr>
<td><label>Gender: </label></td>
<td>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td><label>Mobile: </label></td>
<td>
</td>
</tr>
<tr>
<td><label>Course: </label></td>
<td>
<select name="course">
<option value="CSS">CSS</option>
<option value="JavaScript">JAVASCRIPT</option>
<option value="Java">JAVA</option>
</select>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
Output
UNIT-IV
SERVER-SIDE PROCESSING AND SCRIPTING-PHP
PART-B
PHP is an open source programming and server scripting language that is particularly well
adapted to Create Dynamic web pages and can be includes in HTML codes. It’s used to handle complex
content, databases, and session logging, as well as to create entire e-commerce websites. PHP is generally
known as Hypertext preprocessor but it was first known as Personal Home Page. It was Designed in 1994
by the programmer named Rasmus Lerdorf. PHP would be relatively simple .PHP is compatible with a
variety of databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server,
and can communicate with other services through protocols including LDAP, POP3, HTTP, IMAP, and COM.
And, PHP operates on a variety of platforms, including Windows, Linux, Unix, and Mac OS X,etc.
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
PHP Works:
The PHP program interacts with the site server, which is the program that sends out web pages to the rest
of the world. When you type a URL into the address bar of your web browser, you’re telling the web server
at that URL to email you an HTML file. The requested file is sent by the web server in response. The HTML
file is read by your browser, and then shows the web page. When you press a source on a web page,
you’re also requesting a file from the web server. Additionally, when you press a web page button that
submits a form, the web server processes a file. When PHP is mounted, the procedure is exactly the same.
You submit a file, and the web server, which happens to be running PHP, responds with HTML, because
of PHP it all happens.
Step 3 – Now PHP interpreter will take the Date from Database and responce it back to the Web server.
Step 4 – At last Web server responce to the client who has asked for the page request.
PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable
Example:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!, the
variable $x will hold the value 5, and the variable $y will hold the value 10.5.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
• A variable starts with the $ sign, followed by the name of the variable
• 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)
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:
Example:
<?php
$txt = "Msajce";
echo "I love $txt!";
?>
PHP Variables :
The scope of a variable is the part of the script where the variable can be referenced/used.
• global
• static
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).
Unlike variables, constants are automatically global across the entire script.
Constants are like variables except that once they are defined they cannot be changed or undefined.
Syntax
Parameters:
• case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
Example:
<?php
echo GREETING;
?>
o/p:
Welcome to msajce!
3. Explain PHP operators with example?
PHP Operators:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations,
such as addition, subtraction, multiplication etc.
PHP Assignment Operators:
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
assignment expression on the right.
The PHP comparison operators are used to compare two values (number or string):
PHP Increment / Decrement Operators
PHP has two operators that are specially designed for strings.
The PHP conditional assignment operators are used to set a value depending on conditions:
Conditional statements are used to perform different actions based on different conditions.
• 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
o/p:
o/p:
o/p:
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look
like this:
An array can hold many values under a single name, and you can access the values by referring to an index
number.
PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.
Besides the built-in PHP functions, it is possible to create your own functions.
Syntax
function functionName(){
code to be exeuted;
A function name must start with a letter or an underscore. Function names are NOT case-sensitive.
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates
the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function. The
function outputs "Hello world!". To call the function, just write its name followed by brackets ():
7. Explain File Handling and uploading in PHP?
File handling is an important part of any web application. You often need to open and process a
file for different tasks.
PHP has several functions for creating, reading, uploading, and editing files.
:
PHP Read File - fread()
The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
It's a good programming practice to close all files after you have finished with them. You don't want an
open file running around on your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
PHP Read Single Line - fgets()
The example below outputs the first line of the "webdictionary.txt" file:
Example
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
The example below reads the "webdictionary.txt" file character by character, until end-of-file is reached:
PHP Create File - fopen()
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using
the same function used to open files.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w)
or appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the same directory
where the PHP code resides:
The first parameter of fwrite() contains the name of the file to write to and the second parameter is the
string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing file for
writing. All the existing data will be ERASED and we start with an empty file.
You can append data to a file by using the "a" mode. The "a" mode appends text to the end of the file,
while the "w" mode overrides (and erases) the old content of the file.
PHP File Upload:
However, with ease comes danger, so always be careful when allowing file uploads!
The mail() function allows you to send emails directly from a script.
Requirements
For the mail functions to be available, PHP requires an installed and working email system. The program
to be used is defined by the configuration settings in the php.ini file.
Installation
The mail functions are part of the PHP core. There is no installation needed to use these functions.
Runtime Configuration
MySQL
The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists
of columns and rows.
Databases are useful for storing information categorically. A company may have a database with the
following tables:
• Employees
• Products
• Customers
• Orders
• PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)
Database Queries
We can query a database for specific information and have a recordset returned.
MySQL is the de-facto standard database system for web sites with HUGE volumes of both data and end-
users (like Facebook, Twitter, and Wikipedia).
Another great thing about MySQL is that it can be scaled down to support embedded database
applications.
• MySQLi (object-oriented)
• MySQLi (procedural)
• PDO
UNIT-V
Servlets and Database Connectivity
Servlets Tasks
Servlets perform the following major tasks −
• Read the explicit data sent by the clients (browsers). This
includes an HTML form on a Web page or it could also
come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients
(browsers). This includes cookies, media types and
compression schemes the browser understands, and so
forth.
• Process the data and generate the results. This process
may require talking to a database, executing an RMI or
CORBA call, invoking a Web service, or computing the
response directly.
• Send the explicit data (i.e., the document) to the clients
(browsers). This document can be sent in a variety of
formats, including text (HTML or XML), binary (GIF
images), Excel, etc.
• Send the implicit HTTP response to the clients
(browsers). This includes telling the browsers or other
clients what type of document is being returned (e.g.,
HTML), setting cookies and caching parameters, and
other such tasks.
Servlets Packages
Java Servlets are Java classes run by a web server that has an
interpreter that supports the Java Servlet specification.
Servlets can be created using
the javax.servlet and javax.servlet.http packages, which
are a standard part of the Java's enterprise edition, an
expanded version of the Java class library that supports large-
scale development projects.
These classes implement the Java Servlet and JSP
specifications. At the time of writing this tutorial, the versions
are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any
other Java class. After you install the servlet packages and add
them to your computer's Classpath, you can compile servlets
with the JDK's Java compiler or any other current compiler.
Architecture Diagram
The following figure depicts a typical servlet life-cycle
scenario.
• First the HTTP requests coming to the server are
delegated to the servlet container.
• The servlet container loads the servlet before invoking
the service() method.
• Then the servlet container handles multiple requests by
spawning multiple threads, each thread executing the
service() method of a single instance of the servlet.
Advantages Of Servlets :
1. As servlets support all protocols like FTP, SMTP, HTTP
etc. they can be used to develop any kind of web
applications like E-commerce, Content management
systems, chat based or file based web applications etc.
2. As servlets are fully compatible with Java, you can make
use of wide range of available Java APIs inside the
servlets.
3. As they run on Java enabled servers, You need not to
worry about garbage collection and memory leaks. JVM
handles them for you.
4. Since servlets are written in Java, they are portable and
platform independent. You can run them on any
operating systems and on any web servers available
today.
5. Servlets inherit security features from JVM and web
server.
6. As servlets are written in Java, you can extend them
according to your requirements.
7. As servlets are compiled into bytecodes, they are faster
than any other server-side scripting languages.
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>" +
"</html>"
);
}
}
Assuming your environment is set up properly, compile
HelloForm.java as follows −
$ javac HelloForm.java
If everything goes fine, above compilation would
produce HelloForm.class file. Next you would have to copy
this class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes
and create following entries in web.xml file located in
<Tomcat-installation-directory>/webapps/ROOT/WEB-
INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now
type http://localhost:8080/HelloForm?first_name=ZARA&last
_name=ALI in your browser's Location:box and make sure
you already started tomcat server, before firing above
command in the browser. This would generate following
result −
Using GET Method to Read Form Data
• First Name: ZARA
• Last Name: ALI
GET Method Example Using Form
Here is a simple example which passes two values using
HTML FORM and submit button. We are going to use same
Servlet HelloForm to handle this input.
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Keep this HTML in a file Hello.htm and put it in <Tomcat-
installationdirectory>/webapps/ROOT directory. When you
would access http://localhost:8080/Hello.htm, here is the
actual output of the above form.
First Name: Last Name:
Try to enter First Name and Last Name and then click submit
button to see the result on your local machine where tomcat
is running. Based on the input provided, it will generate
similar result as mentioned in the above example.
POST Method Example Using Form
Let us do little modification in the above servlet, so that it can
handle GET as well as POST methods. Below
is HelloForm.java servlet program to handle input given by
web browser using GET or POST methods.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}
Types of Cookie
There are 2 types of cookies in servlets.
PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time
when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time
when user closes the browser. It is removed only if user
logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Note: Gmail uses cookie technique for login. If you disable the
cookie, gmail won't work.
Cookie class
javax.servlet.http.Cookie class provides the functionality of
using cookies. It provides a lot of useful methods for cookies.
Constructor of Cookie class
Constructor Description
Method Description
public void Sets the maximum age of
setMaxAge(int the cookie in seconds.
expiry)
For adding cookie or getting the value from the cookie, we need some
methods provided by other interfaces. They are:
1. public void addCookie(Cookie ck)
2. public Cookie[] getCookies()
To create Cookie
Let's see the simple code to create cookie.
Cookie ck=new Cookie("user","sonoo jaiswal");//creating
cookie object
response.addCookie(ck);//adding cookie in the response
To delete Cookie
Let's see the simple code to delete cookie. It is mainly used to
logout or signout the user.
Cookie ck=new Cookie("user","");//deleting value of cooki
e
ck.setMaxAge(0);//changing the maximum age to 0 secon
ds
response.addCookie(ck);//adding cookie in the response
How to get Cookies?
Let's see the simple code to get all the cookies.
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//
printing name and value of cookie
}
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie ob
ject
response.addCookie(ck);//adding cookie in the respons
e
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Output
5.Explain Database Connectivity using JDBC?
Database connectivity in servlet. There are different
approaches to communicating with databases through servlet
components. We need to perform the servlet to database
communication due to the following main reasons:-
• To save the inputs coming from the end-user through
forms to database software. Example:- Email Id
registration.
• To save the result generated by servlet Component in
database software. Example:- Bill generation
• To get inputs from the database software to the Servlet
component. Example:- Balance inquiry, account
statement generation
For servlet to database software communication, we need to
place JDBC code/Hibernate code/Spring JDBC/Spring
ORM/Spring Data code in Servlet Component. Since JDBC is
the most basic one therefore here we will discuss servlet to
database communication through JDBC code.
Different Approaches for Database Connectivity in Servlet
There are 4 approaches for Database Connectivity in Servlet.
Approach-1:- Writing logics in multiple methods.
• Create JDBC Connection in the init()
• Use the JDBC Connection in the service(-,-)/doXxx(-,-)
• Close JDBC Connection in the destroy method.
Here JDBC Connection (con) must be taken as an instance
variable of the Servlet Component class.
The disadvantage of this approach:- Since JDBC Connection is
an instance variable, it is not thread-safe by default. So, we
should use the synchronization concept.
Advantage:- All the requests coming to Servlet Component
will use a single JDBC Connection to interact with database
software, due to this the performance will be improved.
Note:- This approach is outdated and nowadays no one is
using this approach (except the maintenance side).
Approach-2:- Write all the logics in service(-,-) or doXxx(-
,-) method.
• Create JDBC Connection in service(-,-)/doXxx(-,-)
method.
• Use JDBC Connection in service(-,-)/doXxx(-,-) method.
• Close JDBC Connection in service(-,-)/doXxx(-,-) method.
Note:- Here JDBC Connection (con) will be a local variable to
service(-,-)/doXxx(-,-) method.
Disadvantage:- The JDBC Connection (con) is a local variable
so, every request which is given to the servlet will create one
JDBC Connection object with database software, hence the
performance will be poor.
Advantage:- Since JDBC Connection is a local variable, it is
thread-safe by default. Hence there is no need to work with
the synchronization concept.
Approach-3:- Use server-managed JDBC connection from
the connection pool.
• Get JDBC Connection object from JDBC Connection pool
being from service(-,-)/doXxx(-,-)
• Use JDBC Connection object in service(-,-)/doXxx(-,-)
• Return JDBC connection back to JDBC connection pool
being from service(-,-)/doXxx(-,-)
Advantage:- Here JDBC connection is local to service(-,-
)/doXxx(-,-) method. So, it becomes thread-safe.
We can get all the advantages of the JDBC connection pool.
The main advantages of the JDBC connection pool are,
• Reusability of JDBC connection objects.
• With minimum JDBC connection objects, we can make
max clients/requests talking with database software.
• Programmer is free from creating connection objects,
managing connection objects, and destroying connection
objects.
Web servers are also supplying existing created JDBC
connections. Therefore programmers should not worry about
how to create JDBC connections, manage them and destroy
them. These tasks will be done by the web server itself. The
programmer will just fetch those JDBC connections and use
them in the servlet component. Moreover, one JDBC
connection can be used for multiple requests, therefore
performance will be good compared to approach2.
Approach4:- Use DAO class for the persistence operation.
What is DAO:- The Java class/component that separates
persistence logic from other logics of the application and
makes that logic as flexible logic to modify and reusable logic
is called DAO (Data access object).
In this approach, we can use either approach-2 or approach-
3 to get the JDBC connection. The main task in this approach,
• Write JDBC code (persistence logic) in DAO class either
by using direct connection object or server-managed
pooled connection object.
• Create a DAO class object in Servlet Component and use
its persistence logic in Servlet Component