Complete AI Notes
Complete AI Notes
Complete AI Notes
Unit - I
HTML:
Basic Text Markup
HTML Styles
HTML Elements
HTML Attributes
Headings
Layouts
Frames
Hypertext Links
Lists
Tables
Forms
Dynamic HTML (DHTML)
CSS
Introduction to CSS
Basic Syntax and Structure of CSS
Using CSS for Background Images, Colors, and Properties
Manipulating Texts and Using Fonts in CSS
Borders, Boxes, Margins, Padding, and Lists in CSS
Positioning Using CSS
The Box Model in CSS
XML (eXtensible Markup Language)
Document Type Definition (DTD) in XML
XML Schemas
Document Object Model (DOM)
Parsers: DOM and SAX
Introduction to XHTML
XML, Meta Tags, and Character Entities
Frames and Frame Sets
Unit - II
JavaScript
Client-Side Scripting
Introduction to JavaScript
Differences Between var, let, and const in JavaScript
Web Technologies 1
Objects:
Primitives:
Operations:
Expressions:
Control Statements in JavaScript
Arrays in JavaScript
Functions:
Types of functions
Constructors:
JavaScript Objects and JavaScript Built-in Objects
The Document Object Model (DOM) and Web Browser Environments
Forms and Validations in Web Development
Introduction to JSP (JavaServer Pages)
The Anatomy of a JSP Page
JSP Processing
Declarations and Directives in JSP
Expressions and Code Snippets in JSP
Implicit Objects in JSP
Using Beans in JSP Pages
Using Cookies and Session for Session Tracking
Connecting to a Database in JSP
Mid Sem
difference between figure and img tag
CSS to control image repetetion
Various Scope Values in JSP
Creating custom tags in JSP
Call Apply and Bind
Unit - 3
Introduction to Server-Side Development with PHP
What is Server-Side Development
A Web Server’s Responsibilities
Quick Tour of PHP
Decision and Looping in PHP with HTML Examples
Decision Making in PHP
Looping Structures in PHP
Integration of PHP and HTML
Arrays in PHP
Functions in PHP
Web Technologies 2
Browser Control and Detection in PHP
Strings in PHP
Form Processing in PHP
File Handling in PHP
Cookies and Sessions in PHP
Unit - 4
PHP and MySQL Integration
Basic commands with PHP examples (PHP and MySQL)
Connection to the Server
Creating and Selecting a Database
Listing Table Names and Creating a Table
Inserting Data and Altering Tables
Executing Queries in PHP
Deleting Database, Tables, and Data
PHPMyAdmin and Database Management
Managing State in Web Applications
The Problem of State in Web Applications
Passing Information via Query Strings
Passing Information via the URL Path
Cookies in Web Applications
Serialization in Web Development
Session State in Web Applications
Unit - I
HTML:
HTML (Hypertext Markup Language) serves as the backbone of web pages,
defining the structure and content. It uses a system of markup tags to describe
the elements within a page.
Basic Structure:
Web Technologies 3
Tags are enclosed in angle brackets (< and >).
Tags usually come in pairs, with an opening tag and a closing tag, denoted
by a forward slash (/) before the tag name.
Example: <tagname>content</tagname>
Attributes:
They are always specified in the start tag and are written as name-value
pairs.
Whitespace:
Extra spaces, tabs, and new lines within HTML code are generally ignored.
Comments:
They are ignored by the browser and are used for adding notes or
explanations within the code.
Case Sensitivity:
<!DOCTYPE html>:
This declaration defines the document type and version of HTML being
used. In modern HTML5 documents, <!DOCTYPE html> is used.
<html> Element:
Web Technologies 4
The <html> element serves as the root element of the HTML document. All
other elements are nested within this element.
<head> Element:
<title> Element:
The <title> element specifies the title of the document, which appears in
the browser's title bar or tab.
<body> Element:
The <body> element contains the content of the web page, including text,
images, links, and other elements visible to the user.
<!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>
Understanding the basic syntax and standard structure of HTML is essential for
creating well-formed web pages that are compatible with different browsers and
devices.
Web Technologies 5
and other text-related elements.
Headings:
HTML provides six levels of headings, from <h1> (the most important) to
<h6> (the least important).
Example:
Paragraphs:
Paragraphs are block-level elements, meaning they start on a new line and
typically have some space above and below them.
Example:
Emphasis:
To emphasize text, you can use the <em> tag or the <strong> tag for
stronger emphasis.
<em> typically renders as italic text, while <strong> renders as bold text.
Example:
Text Formatting:
Web Technologies 6
HTML provides several tags for formatting text, including <i> for italic, <b>
However, these tags are considered outdated in favor of using CSS for
styling.
Example:
Line Breaks:
To insert a line break within a paragraph, you can use the <br> tag.
Example:
Horizontal Rule:
The <hr> tag is used to insert a horizontal rule (or line) to separate
content.
Example:
Comments:
They are not displayed on the web page and do not affect its appearance.
Web Technologies 7
Example:
Understanding basic text markup in HTML allows you to structure and format text
content effectively within your web pages, making them more readable and
visually appealing to users.
HTML Styles
In HTML, styles are used to enhance the appearance of elements on a web page.
Styles can be applied directly within HTML using inline styles, or they can be
defined externally using CSS (Cascading Style Sheets).
Inline Styles:
Inline styles are applied directly to individual HTML elements using the
style attribute.
Example:
Internal Styles:
Internal styles are defined within the <style> element in the <head> section
of the HTML document.
CSS rules are written inside the <style> element and apply to all elements
within the document.
Example:
<head>
<style>
p {
Web Technologies 8
color: blue;
font-size: 16px;
}
</style>
</head>
<body>
<p>This is a paragraph with internal styles.</p>
</body>
External Styles:
External styles are defined in separate CSS files and linked to HTML
documents using the <link> element.
Example:
<head>
<link rel="stylesheet" type="text/css" href="style
s.css">
</head>
HTML Elements
HTML elements are the building blocks of web pages, representing different types
of content such as text, images, links, and multimedia.
Block-level Elements:
Block-level elements start on a new line and take up the full width
available.
Inline Elements:
Inline elements do not start on a new line and only take up as much width
as necessary.
Web Technologies 9
Examples: <span> , <a> , <strong> , <em> , <img> , <br>
HTML Attributes
Attributes provide additional information about HTML elements and are defined
within the opening tag of an element.
Common Attributes:
class : Assigns one or more classes to an element, used for styling with
CSS.
src : Specifies the source URL for elements like images and multimedia.
href : Specifies the URL of the link destination for anchor <a> elements.
Global Attributes:
Event Attributes:
Understanding how to apply styles, use HTML elements effectively, and utilize
attributes allows developers to create visually appealing and interactive web
pages.
Headings
Headings in HTML are used to structure the content of a webpage by indicating
the importance of different sections. HTML offers six levels of headings, ranging
from <h1> (the most important) to <h6> (the least important). These headings not
Web Technologies 10
only organize content but also help search engines understand the hierarchy and
relevance of information.
Usage:
<h1> : Used for main headings or titles. Should be used once per page.
Example:
<h1>Main Heading</h1>
<h2>Subheading</h2>
<h3>Sub-subheading</h3>
Layouts
Layouts in HTML refer to the structure and arrangement of elements within a
webpage. They determine how content is organized and presented to users.
HTML provides various techniques for creating layouts, including using semantic
HTML elements and CSS for styling.
They describe the purpose or role of different parts of the page, making it
easier for developers and assistive technologies to understand the
content.
Example:
<header>
<!-- Header content (e.g., logo, navigation) -->
</header>
<nav>
Web Technologies 11
<!-- Navigation links -->
</nav>
<main>
<!-- Main content of the page -->
<section>
<!-- Section content -->
</section>
<section>
<!-- Another section content -->
</section>
</main>
<footer>
<!-- Footer content (e.g., copyright information) -->
</footer>
CSS Grid and Flexbox are modern CSS layout techniques that allow for
more complex and responsive layouts.
.container {
display: grid;
grid-template-columns: 1fr 1fr; /* Two equal columns */
grid-gap: 20px; /* Gap between grid items */
}
.item {
Web Technologies 12
/* Styles for grid items */
}
https://www.w3schools.com/css/css_grid.asp 🥲
Example (Flexbox):
.container {
display: flex;
justify-content: space-between; /* Distribute items even
ly */
align-items: center; /* Align items vertically */
}
.item {
/* Styles for flex items */
}
Web Technologies 13
Web Technologies 14
Understanding how to use semantic HTML elements and modern CSS layout
techniques allows developers to create well-structured and visually appealing web
layouts that adapt to different screen sizes and devices.
Frames
Frames in HTML allow for the division of a webpage into multiple sections, each
with its own independent HTML document. This technique was commonly used in
the past for creating layouts with multiple, scrollable areas, but it's now largely
deprecated in favor of more modern layout methods like CSS Grid and Flexbox.
Usage:
Attributes:
<frame> :
<frameset> :
rows or cols : Specifies the height or width of each frame within the
frameset.
<iframe> :
Example:
Web Technologies 15
<frame src="content.html" name="content">
</frameset>
Images
Images in HTML are used to display visual content within a webpage, such as
photographs, illustrations, icons, or logos. HTML provides the <img> element for
embedding images into a document.
Usage:
The <img> element is self-closing and does not have a closing tag.
The src attribute specifies the URL or path to the image file.
The alt attribute provides alternative text for the image, which is
displayed if the image cannot be loaded or by screen readers for
accessibility.
The width and height attributes specify the dimensions of the image in
pixels.
Example:
Hypertext Links
Hypertext links, commonly referred to as hyperlinks or simply links, are used to
navigate between different web pages or sections within the same page. HTML
provides the <a> (anchor) element for creating hyperlinks.
Usage:
The <a> element wraps around the content to be linked, typically text or an
image.
The href attribute specifies the URL of the target page or resource.
Optionally, the target attribute can be used to specify where the linked
content should be opened (e.g., in a new window or tab).
Web Technologies 16
Example:
Understanding how to use frames, images, and hypertext links in HTML allows
developers to create engaging and interactive web pages with multimedia content
and navigational elements. However, it's essential to use these features
responsibly and consider accessibility and usability principles.
Lists
Lists in HTML are used to present information in a structured and organized
manner. HTML provides three types of lists: ordered lists ( <ol> ), unordered lists
( <ul> ), and definition lists ( <dl> ).
Ordered lists are used to present items in a sequential order, typically with
numbers or letters.
The type attribute can be used to specify the type of numbering or bullet
style (e.g., numbers, letters, Roman numerals).
Example:
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
Example:
Web Technologies 17
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
Each term is enclosed within a <dt> (definition term) tag, and its definition
is enclosed within a <dd> (definition description) tag.
Example:
<dl>
<dt>Term 1</dt>
<dd>Definition 1</dd>
<dt>Term 2</dt>
<dd>Definition 2</dd>
</dl>
Tables
Tables in HTML are used to display tabular data in rows and columns. The <table>
element is used to define a table, and various other elements such as <tr> (table
row), <th> (table header), and <td> (table data) are used to structure the table.
<th>: Defines a header cell within a row (typically used for column
headings).
Example:
Web Technologies 18
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
<tr>
<td>Data 3</td>
<td>Data 4</td>
</tr>
</table>
Table Attributes:
border : Specifies the width of the border around the table cells.
cellpadding : Specifies the space between the cell content and cell border.
Tables should be used to present tabular data only and not for layout purposes.
It's important to ensure that tables are accessible and semantically structured to
maintain compatibility with assistive technologies and improve usability.
Forms
Forms in HTML are used to collect user input or data. They allow users to enter
text, make selections, and submit data to a server for processing. HTML provides
various form elements such as text fields, checkboxes, radio buttons, dropdown
menus, and buttons.
Web Technologies 19
The <form> element is used to create a form and encloses all form
elements.
The type attribute of the <input> element specifies the type of input field
(e.g., text, password, checkbox).
Other attributes such as name , placeholder , value , and required can be used
to define additional properties of the input field.
Example:
<label for="password">Password:</label>
<input type="password" id="password" name="password" req
uired><br>
Form Attributes:
action : Specifies the URL where the form data should be submitted.
method : Specifies the HTTP method used to submit the form data (e.g.,
"get" or "post").
Web Technologies 20
target: Specifies where to display the response received after submitting
the form (e.g., "_self", "_blank").
Usage:
Event Handling:
DOM Manipulation:
Web Technologies 21
Example (DOM Manipulation):
Understanding how to create and handle forms, as well as manipulate the DOM
using JavaScript, enables developers to build interactive and user-friendly web
applications that respond to user input and behavior.
CSS
Need for CSS
CSS (Cascading Style Sheets) is an essential component of web development,
serving multiple purposes that enhance the appearance, layout, and functionality
of web pages. Below are some key reasons highlighting the need for CSS in
modern web development:
1. Separation of Concerns:
CSS enables the consistent styling of elements across multiple web pages,
ensuring a cohesive look and feel throughout the website. It allows
developers to apply branding elements such as colors, fonts, and logos
consistently, reinforcing brand identity.
3. Responsive Design:
Web Technologies 22
With the proliferation of various devices and screen sizes, responsive
design has become crucial for ensuring optimal user experience. CSS
provides tools such as media queries and flexible layouts to create
responsive designs that adapt to different screen sizes and orientations.
4. Accessibility:
Introduction to CSS
CSS (Cascading Style Sheets) is a style sheet language used to define the
presentation and layout of HTML documents. It allows developers to control the
appearance of web pages by specifying styles for various elements, such as text,
colors, fonts, spacing, and positioning.
Syntax:
The selector specifies which HTML elements the rule applies to, while the
declarations define the styles to be applied, represented as property-value
Web Technologies 23
pairs.
Example:
selector {
property1: value1;
property2: value2;
...
}
Selectors:
Selectors target specific HTML elements based on their type, class, ID,
attributes, or relationship with other elements.
Comments:
CSS allows for comments using /* */ , which are ignored by the browser
and can be used to add notes or explanations within the stylesheet.
Example:
/* This is a comment */
CSS provides the means to create visually appealing and well-structured web
pages, enhancing user experience and facilitating the development of responsive
and accessible designs. Understanding CSS fundamentals is essential for front-
end web developers and designers.
Web Technologies 24
Basic Syntax and Structure of CSS
CSS (Cascading Style Sheets) is a style sheet language used to describe the
presentation of a document written in HTML. It defines how HTML elements
should be displayed on the screen, in print, or in other media. Below is an
overview of the basic syntax and structure of CSS:
1. Syntax:
CSS rules are made up of two main parts: selectors and declarations.
Selectors indicate which HTML elements the style rules should apply to.
Example:
selector {
property1: value1;
property2: value2;
/* more properties */
}
2. Selectors:
They can be based on element names, classes, IDs, attributes, or even the
relationship between elements.
Examples:
Web Technologies 25
Attribute Selector: input[type="text"] { border: 1px solid black; }
3. Comments:
They are used to add notes or explanations within the stylesheet and are
ignored by the browser.
Example:
/* This is a comment */
4. Grouping:
Example:
h1, h2, h3 {
color: red;
font-family: Arial, sans-serif;
}
5. Importing Stylesheets:
CSS files can be imported into other CSS files using the @import rule.
Example:
@import url("styles.css");
6. Media Queries:
Media queries allow for the conditional application of styles based on the
characteristics of the device or viewport, such as screen size, resolution,
or orientation.
Example:
Web Technologies 26
@media screen and (max-width: 600px) {
/* Styles for screens up to 600px wide */
body {
font-size: 14px;
}
}
Understanding the basic syntax and structure of CSS is fundamental for styling
web pages effectively and creating visually appealing and responsive designs.
1. Background Images:
Example:
.container {
background-image: url("background.jpg");
background-repeat: no-repeat;
background-position: center center;
Web Technologies 27
background-size: cover;
}
2. Background Colors:
Example:
.header {
background-color: #f0f0f0; /* Using hexadecimal col
or code */
}
.footer {
background-color: rgb(255, 255, 255); /* Using RGB
color value */
}
Example:
.overlay {
background-color: rgba(0, 0, 0, 0.5); /* Semi-trans
parent black overlay */
}
4. Box Shadows:
Example:
Web Technologies 28
.box {
box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.5); /* Shad
ow with horizontal and vertical offsets, blur radius, a
nd color */
}
5. Border Radius:
rounded corners.
Example:
.rounded {
border-radius: 10px; /* Rounded corners with a radi
us of 10 pixels */
}
6. Text Shadows:
Example:
.text {
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); /* Sha
dow with horizontal and vertical offsets, blur radius,
and color */
}
7. Gradients:
Example:
Web Technologies 29
.gradient {
background-image: linear-gradient(to right, #ff000
0, #0000ff); /* Linear gradient from red to blue */
}
Using CSS properties for background images, colors, and other visual properties,
developers can create engaging and visually appealing web designs that enhance
the user experience. These properties offer flexibility and customization options to
meet the requirements of different projects and design preferences.
1. Font Properties:
Example:
body {
font-family: Arial, sans-serif;
font-size: 16px;
font-weight: bold;
font-style: italic;
font-variant: small-caps;
}
Web Technologies 30
2. Text Alignment:
text-align : Specifies the alignment of text within its container (left, right,
center, justify).
Example:
.center {
text-align: center;
}
3. Text Decoration:
Example:
.underline {
text-decoration: underline;
}
Example:
.spaced {
letter-spacing: 2px;
word-spacing: 5px;
}
5. Text Transform:
Example:
Web Technologies 31
.uppercase {
text-transform: uppercase;
}
6. Line Height:
Example:
.line-height {
line-height: 1.5;
}
7. Font Color:
Example:
.red-text {
color: red;
}
Google Fonts provides a wide range of free, open-source fonts that can be
easily integrated into web projects.
Developers can include Google Fonts in their CSS using the @import rule or
by linking to the font stylesheet in the HTML document.
Example:
@import url('<https://fonts.googleapis.com/css2?family=
Roboto:wght@400;700&display=swap>');
body {
Web Technologies 32
font-family: 'Roboto', sans-serif;
}
By using these CSS properties for text manipulation and font styling, developers
can create visually appealing typography and enhance the readability and
aesthetics of web content. Customizing fonts and text properties allows for
greater flexibility in design and branding, contributing to a more engaging user
experience.
1. Borders:
border : Sets the width, style, and color of the border around an element.
It's shorthand for border-width , border-style , and border-color .
border-style : Sets the style of the border (e.g., solid, dashed, dotted).
Example:
.element {
border: 1px solid #000;
}
2. Boxes:
box-sizing : Defines how the width and height of an element are calculated
(e.g., content-box, border-box).
Example:
Web Technologies 33
.element {
width: 200px;
height: 100px;
box-sizing: border-box;
}
3. Margins:
margin : Sets the margin (space) around an element. It can have different
values for top, right, bottom, and left sides.
Example:
.element {
margin: 10px; /* All sides */
margin-top: 10px; /* Top side */
margin-bottom: 20px; /* Bottom side */
}
4. Padding:
padding : Sets the padding (space) between the content and the border of
an element. It can have different values for top, right, bottom, and left
sides.
Example:
.element {
padding: 10px; /* All sides */
padding-top: 10px; /* Top side */
padding-bottom: 20px; /* Bottom side */
}
5. Lists:
list-style-type : Specifies the type of marker for list items (e.g., disc, circle,
square, decimal, lower-alpha, upper-roman).
Web Technologies 34
list-style-image : Specifies an image as the marker for list items.
Example:
ul {
list-style-type: disc;
}
By using these CSS properties, developers can create visually appealing layouts
with customized borders, boxes, margins, padding, and lists. These properties
provide flexibility in designing web pages and help improve the overall user
experience by enhancing the presentation and organization of content.
1. Static Positioning:
2. Relative Positioning:
position: relative; moves the element relative to its normal position on the
page.
Other elements are not affected by the relative positioning of the element.
Example:
.relative {
position: relative;
top: 20px;
Web Technologies 35
left: 10px;
}
3. Absolute Positioning:
Example:
.absolute {
position: absolute;
top: 50px;
left: 50px;
}
4. Fixed Positioning:
Example:
.fixed {
position: fixed;
top: 0;
right: 0;
}
5. Z-index:
Elements with a higher z-index value appear above elements with a lower
value.
Example:
Web Technologies 36
.higher-z-index {
position: relative;
z-index: 10;
}
.lower-z-index {
position: relative;
z-index: 5;
}
6. Float:
Example:
.float-left {
float: left;
}
.float-right {
float: right;
}
7. Clear:
clear specifies which sides of an element other floating elements are not
allowed to float.
Example:
.clear-left {
clear: left;
}
.clear-right {
clear: right;
}
Web Technologies 37
These positioning properties in CSS provide developers with powerful tools to
create complex layouts and achieve desired visual effects on web pages. By
understanding how to use these properties effectively, developers can design
responsive and visually appealing websites.
1. Content:
The content area of an element is where the actual content, such as text or
images, is displayed.
2. Padding:
Padding is the space between the content area and the element's border.
It can be set using the padding property and can have different values for
each side (top, right, bottom, left).
3. Border:
color .
Borders can have different styles (solid, dashed, dotted) and thicknesses.
4. Margin:
Web Technologies 38
They can be set using the margin property and can have different values
for each side (top, right, bottom, left).
___________________________
| Margin |
| _______________________ |
| | Border | |
| | ___________________ | |
| | | Padding | | |
| | | _______________ | | |
| | | | Content | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |_______________| | | |
| | |___________________| | |
| |_______________________| |
|___________________________|
Example:
.box {
width: 200px;
height: 100px;
padding: 20px; /* Adds 20px of padding inside the border
*/
border: 2px solid black; /* Creates a 2px solid black bor
der around the padding */
margin: 10px; /* Adds 10px of margin outside the border
*/
}
Web Technologies 39
In summary, the box model in CSS defines the dimensions and spacing of
elements on a web page, including the content area, padding, border, and margin.
By understanding and manipulating these components, developers can create
well-structured layouts and achieve desired spacing and visual effects in their
designs.
Elements are the building blocks of XML documents and represent structured
data.
Elements are enclosed within start tags ( <element> ) and end tags ( </element> ).
Example:
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
2. Attributes:
Example:
Web Technologies 40
<book category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
3. Text Content:
Example:
4. Hierarchical Structure:
Example:
<library>
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
</book>
</library>
5. Well-Formedness Rules:
Web Technologies 41
XML documents must adhere to certain well-formedness rules, such as having
a single root element, properly nested elements, and quoted attribute values.
Generic Example:
Web Technologies 42
for id , and child elements for name , department , and salary . This demonstrates
how XML can be used to structure and represent data in a hierarchical and self-
descriptive manner.
DTD (Document Type Definition) for Employee XML Example
A DTD (Document Type Definition) is a formal specification that defines the
structure, elements, attributes, and their relationships within an XML document. It
provides a set of rules that validate the structure and content of an XML
document. Here's a DTD for the employee XML example:
<!DOCTYPE employees [
<!ELEMENT employees (employee*)>
<!ELEMENT employee (name, department, salary)>
<!ATTLIST employee
id ID #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT department (#PCDATA)>
<!ELEMENT salary (#PCDATA)>
]>
Explanation:
<!DOCTYPE> : Declares the document type and specifies the root element
( employees ).
: Defines the
<!ELEMENT name (#PCDATA)> name element as containing parsed
character data (#PCDATA).
Web Technologies 43
<!ELEMENT salary (#PCDATA)> : Defines the salary element as containing parsed
character data.
Explanation:
Web Technologies 44
xs:complexType : Defines the structure of complex types (elements with child
elements).
element.
These DTD and XML Schema examples provide a formal definition of the structure
and constraints of the employee XML document, ensuring its validity and
consistency.
Web Technologies 45
Document Type Definition (DTD) in XML
Document Type Definition (DTD) is a markup declaration that defines the
structure, elements, and attributes allowed within an XML document. It serves as a
schema for validating the structure and content of XML documents. Here's an
overview of DTD in XML:
1. Purpose of DTD:
DTD defines the rules and constraints for the structure and content of XML
documents.
It specifies the elements and attributes that can appear in the document
and their relationships.
DTD allows for validation of XML documents to ensure they conform to the
specified rules.
2. Syntax:
DTDs are declared within the XML document using the DOCTYPE declaration.
Web Technologies 46
The DOCTYPE declaration consists of the keyword DOCTYPE , the root element
name, and a reference to the external DTD file or an internal DTD
declaration.
<!DOCTYPE rootElementName [
<!-- DTD declarations -->
]>
3. Element Declarations:
Element declarations specify the elements that can appear in the XML
document.
Syntax:
Example:
4. Attribute Declarations:
Syntax:
Example:
Web Technologies 47
<!ATTLIST book category CDATA #IMPLIED>
5. Entity Declarations:
Syntax:
Example:
6. Validation:
XML parsers can validate XML documents against a DTD to ensure they
adhere to the specified structure and constraints.
Validation can be performed during parsing, and errors are reported if the
document does not conform to the DTD.
DTDs provide a formal way to define the structure and content of XML documents,
enabling validation and ensuring consistency in data exchange. They are
commonly used in various XML-based technologies, such as XHTML, RSS, and
SOAP, to define document structures and validate data integrity.
XML Schemas
XML Schema Definition (XSD) is a World Wide Web Consortium (W3C)
recommendation that defines the structure, data types, and constraints for XML
documents. It serves as an alternative to Document Type Definition (DTD) for
defining the structure and content of XML documents. Here's an overview of XML
schemas:
Web Technologies 48
XML Schema provides a more powerful and flexible way to define the
structure and content of XML documents compared to DTD.
2. Syntax:
XML schemas are written in XML syntax and can be declared within the
XML document or as separate XSD files.
<xs:schema xmlns:xs="<http://www.w3.org/2001/XMLSchema
>">
<!-- Schema declarations -->
</xs:schema>
3. Element Declarations:
XML Schema allows for the declaration of elements using the xs:element
element.
Example:
Web Technologies 49
<xs:element name="book" type="xs:string"/>
4. Attribute Declarations:
Example:
5. Complex Types:
Complex types define elements with child elements or mixed content (both
text and child elements).
Example:
<xs:complexType name="bookType">
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
</xs:sequence>
</xs:complexType>
6. Simple Types:
Simple types define atomic data types such as strings, numbers, dates,
etc.
Example:
<xs:simpleType name="yearType">
<xs:restriction base="xs:gYear"/>
Web Technologies 50
</xs:simpleType>
XML schemas provide a robust framework for defining the structure, data types,
and constraints of XML documents. They offer enhanced validation capabilities
compared to DTDs and are widely used in various XML-based technologies such
as SOAP, XML Schema-based validation, and XML data serialization.
Here's a comparison table highlighting the differences between DTD (Document
Type Definition) and XML Schema (XSD):
Namespace
Does not support namespaces Supports namespaces
Support
Summary:
DTDs have a simpler syntax and are supported by older systems, but they lack
features such as namespace support and strong data typing.
XML Schema (XSD) provides more flexibility and expressive power, supporting
namespaces, data types, inheritance, and modularity, making it a more
modern and widely used standard for defining XML structures and constraints.
Web Technologies 51
The Document Object Model (DOM) is a programming interface for web
documents that represents the structure of HTML, XHTML, and XML documents
as a tree-like structure, where each node represents a part of the document, such
as elements, attributes, and text. DOM provides a platform- and language-neutral
interface that allows programs and scripts to dynamically access and manipulate
the content, structure, and style of web documents. Here's an overview of DOM:
1. Tree Structure:
The root of the tree is typically the document node, representing the entire
document.
Child nodes are nested within their parent nodes, forming a tree-like
structure that mirrors the document's markup.
2. Nodes:
Element nodes represent HTML or XML elements, such as <div> , <p> , <a> ,
etc.
Web Technologies 52
Developers can traverse the DOM tree, navigate between nodes, and
retrieve or modify their attributes and content using JavaScript or other
programming languages.
4. Event Handling:
DOM is a powerful and versatile API that plays a crucial role in web development,
enabling the creation of dynamic, interactive, and accessible web applications. It
provides a standardized interface for working with web documents across
different platforms and programming languages, making it a fundamental part of
modern web development.
Overview:
Web Technologies 53
The DOM parser loads the entire XML document into memory and
represents it as a tree-like structure, called the DOM tree.
Usage:
Provides a convenient and intuitive API for working with XML data,
making it easier to navigate and manipulate document contents.
Pros:
Cons:
Requires loading the entire XML document into memory, which may
not be efficient for large documents.
Overview:
Web Technologies 54
Usage:
Pros:
Low memory usage, as it does not require loading the entire document
into memory.
Cons:
In summary, DOM and SAX parsers are both valuable tools for parsing XML
documents in different scenarios. DOM provides a convenient API for working with
XML data when random access to different parts of the document is required,
while SAX offers efficient event-based parsing for processing large XML
documents or streaming XML data with minimal memory overhead. Developers
should choose the appropriate parser based on their specific requirements and
the characteristics of the XML data being processed.
Introduction to XHTML
XHTML (Extensible Hypertext Markup Language) is a markup language that
extends the capabilities of HTML (Hypertext Markup Language) by conforming to
the stricter syntax rules of XML (Extensible Markup Language). XHTML combines
the flexibility and simplicity of HTML with the well-formedness and extensibility of
XML, making it suitable for creating structured, well-formed web documents.
Here's an overview of XHTML:
1. XML Syntax:
Web Technologies 55
XHTML documents are well-formed XML documents, which means they
adhere to the syntax rules of XML.
XHTML documents must have a single root element and all elements must
be properly nested.
2. Stricter Rules:
4. XHTML Doctype:
5. Advantages of XHTML:
Web Technologies 56
XHTML documents are more accessible and device-independent, making
them suitable for a wide range of devices and platforms.
Web Technologies 57
background-color: #ffffff;
padding: 20px;
border: 1px solid #cccccc;
}
h1 {
color: #006699;
}
p {
line-height: 1.5;
}
</style>
</head>
<body>
<div id="container">
<h1>XHTML Example</h1>
<p>This is a simple example of an XHTML document.</p>
<p>It demonstrates the basic structure and syntax of
XHTML.</p>
</div>
</body>
</html>
Explanation:
The <!DOCTYPE> declaration specifies the document type and DTD (Document
Type Definition) for XHTML 1.0 Transitional.
The <html> element defines the root element of the document and includes the
XML namespace declaration.
The <head> section contains meta information such as the character encoding
and title of the document.
CSS styles are embedded within a <style> element to define the visual
presentation of the document.
The <body> section contains the content of the document, enclosed within a
<div> element with the id "container".
Web Technologies 58
Semantic markup elements such as <h1> for headings and <p> for paragraphs
are used to structure the content.
The CSS styles define the appearance of the content, including font family,
colors, margins, and padding.
This example demonstrates the basic structure of an XHTML document and how
CSS can be used to style the content for presentation on the web.
Overview:
XML is widely used for data interchange between different systems and
platforms.
Syntax:
Elements are enclosed in angle brackets < > and may have attributes in
the form of name-value pairs.
Example:
<book>
<title>XML Guide</title>
<author>John Doe</author>
</book>
Meta Tags:
Overview:
Web Technologies 59
Meta tags are HTML or XHTML elements that provide metadata about a
web page, such as its title, description, keywords, author, etc.
They are typically placed within the <head> section of an HTML document
and are not displayed on the web page itself.
Meta tags help search engines understand the content and context of the
web page and improve its visibility in search results.
Character Entities:
Overview:
They allow you to display characters that are reserved for HTML or XML
syntax, such as < , > , & , etc., without causing parsing errors.
Example:
XML, meta tags, and character entities are essential components of web
development, providing mechanisms for creating structured, well-formatted
documents and improving the accessibility and visibility of web pages in search
Web Technologies 60
engines. Understanding how to use them effectively is important for creating high-
quality, standards-compliant web content.
Frames are a feature in HTML that allow a webpage to be divided into multiple
independent sections, each of which can display a different document.
Each frame acts as a separate window within the browser, enabling different
content to be displayed simultaneously.
Frames are typically created using the <frame> or <iframe> elements in HTML.
Frame Sets:
Frame sets define the layout of frames within the webpage, specifying their
size, position, and arrangement.
Frames within a frame set are defined using the <frame> element, which
specifies the content to be displayed in each frame.
<!DOCTYPE html>
<html>
<head>
<title>Frame Set Example</title>
</head>
<frameset cols="25%,75%">
<frame src="menu.html" name="menu">
<frame src="content.html" name="content">
<noframes>
<body>
This page requires a browser that supports frame
s.
</body>
Web Technologies 61
</noframes>
</frameset>
</html>
The <frameset> element defines a frame set with two columns, where the
first column occupies 25% of the width and the second column occupies
75%.
Two frames are defined within the frame set using the <frame> element.
The src attribute specifies the URL of the document to be displayed in
each frame, and the name attribute provides a name for the frame.
Considerations:
Frames and frame sets were widely used in earlier versions of HTML for
creating multi-pane layouts, such as navigation menus, headers, and content
areas.
As a result, frames are not commonly used in modern web development, and
alternative techniques, such as CSS layout techniques and server-side
includes, are preferred for creating flexible and accessible layouts.
While frames and frame sets were once popular for creating multi-pane layouts in
web development, they have largely been replaced by more modern and flexible
techniques. It's important for web developers to be aware of frames and their
capabilities, but they should also consider using alternative approaches that offer
better accessibility, usability, and SEO benefits.
Unit - II
JavaScript
Web Technologies 62
JavaScript is a high-level, interpreted programming language that is widely used
for creating dynamic and interactive web pages. It is an essential component of
web development, allowing developers to add behavior, interactivity, and
functionality to web pages. Here's an overview of JavaScript:
1. Client-Side Scripting:
2. Syntax:
Variables are declared using the var , let , or const keywords, and can
store values of any data type.
Example:
4. Functions:
Web Technologies 63
Functions in JavaScript are blocks of code that can be executed when
called.
Example:
function greet(name) {
return "Hello, " + name + "!";
}
5. DOM Manipulation:
Example:
6. Events:
method.
Example:
Web Technologies 64
document.getElementById("myButton").addEventListener("c
lick", function() {
alert("Button clicked!");
});
JavaScript is a versatile and powerful language that plays a crucial role in modern
web development. It provides the foundation for creating dynamic, interactive, and
responsive web pages, enhancing user experience and functionality. With its
broad adoption and extensive ecosystem of libraries and frameworks, JavaScript
continues to evolve and innovate, driving innovation in web development.
Client-Side Scripting
Client-side scripting refers to the execution of scripts or programming code within
the user's web browser, as opposed to on the server. It allows developers to
enhance the functionality and interactivity of web pages by dynamically
manipulating the content, behavior, and appearance of the page in response to
user actions and events. Here's an overview of client-side scripting:
1. Languages Used:
2. Execution Environment:
Client-side scripts are executed within the context of the user's web
browser, such as Google Chrome, Mozilla Firefox, Microsoft Edge, etc.
Scripts are embedded directly within HTML documents using the <script>
element, or they can be included as separate script files using the src
attribute.
Web Technologies 65
JavaScript code is downloaded along with the HTML document and
executed by the browser as it parses the document.
3. Functionality:
Common use cases for client-side scripting include form validation, DOM
manipulation, event handling, animations, AJAX requests, and browser
cookies handling.
4. DOM Manipulation:
5. Event Handling:
method in JavaScript.
6. Browser Compatibility:
Web Technologies 66
Client-side scripting is a fundamental aspect of web development, enabling
developers to create dynamic, interactive, and responsive web applications that
deliver rich user experiences. By leveraging the capabilities of client-side scripting
languages such as JavaScript, developers can create modern and engaging web
interfaces that enhance user engagement and satisfaction.
Introduction to JavaScript
JavaScript is a versatile programming language primarily used for creating
dynamic and interactive web pages. It is an essential component of web
development, allowing developers to add functionality, interactivity, and behavior
to websites. Here's an overview of JavaScript:
1. Client-Side Scripting:
2. Syntax:
Variables are declared using the var , let , or const keywords, and can
store values of any data type.
4. Functions:
Web Technologies 67
They can accept parameters and return values.
5. DOM Manipulation:
6. Event Handling:
method.
7. Browser Compatibility:
JavaScript is a powerful and versatile language that plays a crucial role in modern
web development. It enables developers to create dynamic, interactive, and
responsive web applications that deliver rich user experiences. With its broad
adoption and extensive ecosystem of libraries and frameworks, JavaScript
continues to evolve and innovate, driving innovation in web development.
Web Technologies 68
In JavaScript, var , let , and const are used to declare variables, but they have
some differences in terms of scope, hoisting, and mutability. Here's an explanation
of each, along with examples:
1. var:
Variables declared with var are function-scoped or globally scoped, but not
block-scoped.
Variables declared with var can be re-declared and updated within their
scope.
Example:
var x = 10;
if (true) {
var x = 20; // re-declaration
console.log(x); // Output: 20
}
console.log(x); // Output: 20 (updated value)
2. let:
let was introduced in ES6 (ECMAScript 2015) to address some of the issues
with var .
Variables declared with let are block-scoped, meaning they are only
accessible within the block they are declared in.
Variables declared with let can be updated within their scope, but not re-
declared in the same scope.
Example:
let x = 10;
if (true) {
let x = 20;
console.log(x); // Output: 20
Web Technologies 69
}
console.log(x); // Output: 10
3. const:
const is also introduced in ES6 and is used to declare constants, whose value
cannot be changed once assigned.
Unlike var and let , variables declared with const must be initialized at the
time of declaration, and they cannot be reassigned a new value.
Example:
const x = 10;
x = 20; // Error: Assignment to constant variable.
var allows re-declaration and updating within its scope, while let allows
updating but not re-declaration, and const does not allow re-assignment after
initialization.
let and const provide better control over variable scope and mutability
compared to var , and are recommended for modern JavaScript development.
Note: It's good practice to use const by default for variables that won't be
reassigned, and let for variables that need to be reassigned. Use var only when
you specifically need its function-scoping behavior or for compatibility with older
JavaScript code.
Objects:
Web Technologies 70
In JavaScript, an object is a collection of key-value pairs, where each key is a
string (or symbol) and each value can be of any data type, including other
objects.
Objects can have properties (key-value pairs) and methods (functions that are
associated with the object).
// Creating an object
var person = {
name: "John",
age: 30,
city: "New York"
};
Primitives:
In JavaScript, primitives are data types that are not objects and have no methods
or properties. They are immutable, meaning their values cannot be changed.
JavaScript has six primitive data types:
Web Technologies 71
let age = 25;
let pi = 3.14;
5. Undefined: Represents a variable that has been declared but has not been
assigned a value.
let city;
These primitive data types are compared by their value, not by reference, which
means two variables containing the same primitive value are considered equal.
Primitives are stored directly in memory, while objects and arrays are stored by
reference.
Here's an example to demonstrate how primitives work:
let a = 5;
let b = a; // b is assigned the value of a
console.log(a); // Output: 5
console.log(b); // Output: 5
Web Technologies 72
console.log(a); // Output: 10
console.log(b); // Output: 5 (b remains unchanged)
In this example, changing the value of a does not affect the value of b because
they are separate variables holding their own primitive values.
Operations:
JavaScript supports various operations for performing arithmetic, comparison,
logical, assignment, and other operations.
(decrement).
Comparison operators include == , === , != , !== , < , > , <= , and >= .
Logical operators include && (logical AND), || (logical OR), and ! (logical
NOT).
Example of operations:
// Arithmetic operations
var sum = 10 + 5; // Addition
var difference = 10 - 5; // Subtraction
var product = 10 * 5; // Multiplication
var quotient = 10 / 5; // Division
var remainder = 10 % 3; // Modulo
// Comparison operations
var isEqual = (10 == 5); // false
var isGreater = (10 > 5); // true
// Logical operations
var result = (true && false); // false
var negation = !true; // false
Web Technologies 73
// Assignment operations
var x = 5;
x += 2; // Equivalent to: x = x + 2;
here's a code block demonstrating some JavaScript operators that may not be as
common in other programming languages 😈:
// JavaScript Specific Operators
Web Technologies 74
address: {
city: 'New York'
}
};
Expressions:
Expressions in JavaScript are combinations of values, variables, operators,
and function calls that produce a single value.
Example of expressions:
Web Technologies 75
// Arithmetic expression
var result = 10 + (5 * 2); // Output: 20
// Logical expression
var isValid = (age >= 18) && (age <= 65);
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Web Technologies 76
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if all conditions are false
}
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
default:
// Code to execute if expression doesn't match any
case
}
2. Looping Statements:
Looping statements are used to repeat code blocks until a specified condition is
met. JavaScript provides several looping statements:
Web Technologies 77
while (condition) {
// Code to execute as long as condition is true
}
do...while loop: Similar to a while loop, but it always executes the code block
at least once before checking the condition.
do {
// Code to execute at least once
} while (condition);
for...of loop (ES6): Iterates over iterable objects such as arrays, strings, maps,
sets, etc.
continue statement: Skips the current iteration of a loop and continues with
the next iteration.
Web Technologies 78
Control statements are essential for writing flexible and dynamic JavaScript code.
They allow developers to create logic that responds to different conditions and
iterates over collections of data, enabling the creation of powerful and interactive
web applications. Understanding how to use control statements effectively is
crucial for mastering JavaScript programming.
Arrays in JavaScript
Arrays are a fundamental data structure in JavaScript that allow developers to
store multiple values in a single variable. They are commonly used for organizing
and manipulating collections of data. Here's an overview of arrays in JavaScript:
1. Creating Arrays:
Arrays in JavaScript are created using square brackets [] and can contain
any number of elements separated by commas.
Example:
Example:
Web Technologies 79
length : Returns the number of elements in the array.
pop() : Removes the last element from the array and returns it.
Example:
console.log(fruits.length); // Output: 3
fruits.push('grape'); // Add 'grape' to the e
nd of the array
console.log(fruits); // Output: ['apple', 'b
anana', 'orange', 'grape']
var lastFruit = fruits.pop(); // Remove and return th
e last element ('grape')
console.log(lastFruit); // Output: 'grape'
console.log(fruits.join(', ')); // Output: 'apple, bana
na, orange'
Arrays can be iterated using various looping constructs such as for loops,
while loops, and forEach() method.
Example:
Web Technologies 80
console.log(fruit);
});
5. Multidimensional Arrays:
Example:
var matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][1]); // Output: 2
Arrays are versatile and widely used in JavaScript for storing and manipulating
collections of data. Understanding how to work with arrays effectively is essential
for building dynamic and interactive web applications. By leveraging the
properties, methods, and iteration techniques provided by JavaScript arrays,
developers can create powerful and efficient solutions to a wide range of
programming challenges.
Functions:
1. Function Declaration:
Example:
Web Technologies 81
function greet(name) {
return 'Hello, ' + name + '!';
}
2. Function Expression:
Example:
Example:
4. Invoking Functions:
Example:
Arguments are the actual values passed to the function when it is invoked.
Web Technologies 82
Example:
function add(a, b) {
return a + b;
}
var sum = add(5, 3); // Output: 8
Types of functions
js 👎😭
// 1. Function Declaration
function add(a, b) {
return a + b;
}
// 3. Arrow Function
let multiply = (a, b) => a * b;
// 4. Function Constructor
let divide = new Function('a', 'b', 'return a / b');
Web Technologies 83
// 5. Immediately Invoked Function Expression (IIFE)
(function() {
let message = 'Hello, IIFE!';
console.log(message); // Output: Hello, IIFE!
})();
// 6. Generator Function
function* generateSequence() {
yield 1;
yield 2;
yield 3;
}
console.log(sequence.next().value); // Output: 1
console.log(sequence.next().value); // Output: 2
console.log(sequence.next().value); // Output: 3
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
Web Technologies 84
Arrow Function defines a function named multiply using the arrow function
syntax.
Constructors:
Constructors in JavaScript are special functions used for creating and initializing
objects. They serve as blueprints for creating multiple instances of similar objects
with the same properties and methods. Here's an overview of constructors in
JavaScript:
1. Creating Constructors:
Example:
Objects are created using the new keyword followed by the constructor
function name and any arguments required by the constructor.
Example:
Web Technologies 85
var person1 = new Person('John', 30);
Constructor functions can define properties and methods that are shared
by all instances created with that constructor.
Example:
1. Creating Objects:
Web Technologies 86
Object literals are the simplest way to create objects and are defined
within curly braces {} .
var person = {
name: 'John',
age: 30,
city: 'New York'
};
Example:
Example:
4. Deleting Properties:
Example:
Web Technologies 87
JavaScript Built-in Objects:
JavaScript provides a set of built-in objects that provide functionality beyond
basic data types. These built-in objects are part of the JavaScript language
specification and are available for use in all JavaScript environments, such as web
browsers and Node.js. Here are some commonly used JavaScript built-in objects:
1. Math Object:
Example:
2. Date Object:
The Date object represents dates and times and provides methods for
working with dates and times.
Example:
3. Array Object:
The Array object provides methods and properties for working with arrays,
such as adding/removing elements, iterating over elements, and searching
for elements.
Example:
4. String Object:
Web Technologies 88
Although strings are primitive data types, JavaScript provides a String
Example:
JavaScript built-in objects provide additional functionality and utility beyond basic
data types, enabling developers to perform a wide range of tasks efficiently. By
leveraging built-in objects and understanding how to work with objects in
JavaScript, developers can create powerful and sophisticated applications with
ease.
1. Tree Structure:
The top-level node is called the document node, which represents the
entire HTML document.
Nodes are the fundamental building blocks of the DOM tree and can
represent elements, attributes, or text.
Elements are nodes that represent HTML elements such as <div> , <p> ,
<span> , etc.
Web Technologies 89
3. Accessing and Manipulating Elements:
4. Event Handling:
The DOM allows JavaScript to respond to user actions and browser events
using event handlers.
Event handlers can be attached to HTML elements to listen for events such
as clicks, mouse movements, keyboard input, etc.
5. Dynamic Updates:
This allows for the creation of interactive and responsive web applications.
1. Rendering Engine:
2. JavaScript Engine:
Each browser has its own JavaScript engine, such as V8 (used in Google
Chrome), SpiderMonkey (used in Mozilla Firefox), and JavaScriptCore
(used in Safari).
Web Technologies 90
3. Web APIs:
These APIs include the DOM API for manipulating HTML documents, the
Fetch API for making HTTP requests, the Web Storage API for storing data
locally in the browser, and many others.
4. Security:
The combination of the DOM and web browser environments provides a powerful
platform for developing web applications. By understanding how to work with the
DOM and leverage web browser APIs, developers can create rich, interactive, and
secure web experiences for users.
1. Form Structure:
The <form> element is used to create a form, and it can contain one or
more input elements.
Each input element may have attributes like type , name , id , value , etc., to
specify its type and characteristics.
2. Submitting Forms:
Web Technologies 91
When a user submits a form, the data entered into the input fields is sent
to the server for processing.
3. Form Validation:
Form validation is the process of ensuring that user input meets certain
requirements before it is submitted to the server.
Form Validations:
Form validations are used to ensure that the data entered into form fields meets
specific criteria before it is submitted. Common validation techniques include:
1. Required Fields:
Ensure that certain fields are not left empty before submission.
Example:
Validate the length of input fields to ensure they meet certain length
requirements.
Example:
3. Pattern Matching:
Example:
Web Technologies 92
<input type="text" name="email" pattern="[a-z0-9._%+-]+
@[a-z0-9.-]+\\.[a-z]{2,}$">
Example:
function validatePassword() {
var password = document.getElementById('password').
value;
// Custom validation logic
if (password.length < 8) {
alert('Password must be at least 8 characters l
ong.');
return false;
}
return true;
}
5. Feedback Mechanisms:
Web Technologies 93
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-sc
ale=1.0">
<title>Form Validation</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h2>Login Form</h2>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" requir
ed><br>
<span id="passwordError" class="error"></span><br>
<script>
function validateForm() {
let password = document.getElementById('password').value;
if (password.length < 8) {
document.getElementById('passwordError').textContent = 'P
assword must be at least 8 characters long';
return false;
Web Technologies 94
}
return true;
}
</script>
</body>
</html>
The required attribute is used in HTML to ensure both fields are filled out
before submission.
1. Server-Side Technology:
This allows for the creation of dynamic and interactive web applications
that can respond to user input and generate personalized content.
JSP pages contain both HTML markup and Java code, making it easy for
developers to integrate dynamic content generation with standard HTML
presentation.
Web Technologies 95
Java code is enclosed within special tags <% %> or <%= %> , allowing it to be
executed within the context of the JSP page.
3. Servlet-Based Technology:
Under the hood, JSP pages are converted into Java servlets by the web
container (e.g., Apache Tomcat, Jetty, etc.) before they are executed.
This means that JSP pages ultimately execute as Java servlets, leveraging
the power and flexibility of the Java Servlet API.
This allows for the creation of web applications that can adapt to changing
data and user interactions in real-time.
5. Reusable Components:
JSP pages can include reusable components called tag libraries, which
encapsulate common functionality and simplify development.
Tag libraries provide predefined tags that can be used to perform tasks
such as database access, session management, authentication, and more.
6. MVC Architecture:
Overall, JSP is a powerful technology for building dynamic and interactive web
applications in Java. By combining the strengths of Java and HTML, developers
can create feature-rich web pages that deliver a compelling user experience and
meet the demands of modern web development.
Web Technologies 96
Below is a simple example of a generic web application using JavaServer Pages
(JSP). This application consists of two JSP pages: one for the input form and one
for displaying the submitted data.
index.jsp (Input Form)
<!DOCTYPE html>
<html>
<head>
<title>Simple WebApp</title>
</head>
<body>
<h2>Input Form</h2>
<form action="submit.jsp" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br
><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
Web Technologies 97
</head>
<body>
<h2>Submitted Data</h2>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
%>
<p><strong>Name:</strong> <%= name %></p>
<p><strong>Email:</strong> <%= email %></p>
</body>
</html>
In this example:
index.jsp displays a simple input form with fields for name and email. When
the form is submitted, it sends the data to submit.jsp for processing.
1. Save the index.jsp and submit.jsp files in the web application directory (e.g.,
webapp or webContent ).
4. Enter some data in the input form and click the "Submit" button. The submitted
data will be displayed on the submit.jsp page.
1. Directive Tags:
Web Technologies 98
Directive tags provide instructions to the JSP container about how to
process the page.
<%@ taglib %> : Declares a custom tag library for use in the JSP page.
2. Declaration Section:
The declaration section allows you to declare variables and methods that
can be used throughout the JSP page.
Example:
<%!
int count = 0;
String message = "Welcome!";
void incrementCount() {
count++;
}
%>
3. Scriptlet Section:
The scriptlet section contains Java code that is executed when the JSP
page is processed.
Example:
Web Technologies 99
<%
String username = request.getParameter("username");
if (username != null) {
out.println("Hello, " + username + "!");
}
%>
4. Expression Section:
The result of the expression is converted to a string and inserted into the
HTML output.
Example:
5. Directive Body:
The directive body contains HTML markup that defines the structure and
presentation of the web page.
It includes standard HTML tags such as <html> , <head> , <body> , <div> , <p> ,
etc.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My JSP Page</title>
</head>
<body>
<h1>Hello, world!</h1>
6. Comments:
Example:
JSP Processing
JSP (JavaServer Pages) processing involves several steps, from the initial request
to the server to the generation of dynamic HTML content sent back to the client's
web browser. Understanding the JSP processing lifecycle is essential for
developing and debugging JSP-based web applications. Here's an overview of the
typical steps involved in JSP processing:
1. Client Request:
The JSP processing lifecycle begins when a client sends an HTTP request
to the server for a specific JSP page.
The request can include parameters, cookies, headers, and other data
sent by the client.
2. Web Container:
The web container (e.g., Apache Tomcat, Jetty, etc.) receives the client
request and locates the corresponding JSP file on the server's file system.
During the translation phase, the web container translates the JSP page
into a servlet.
This involves converting the JSP page's HTML markup and embedded
Java code into equivalent Java code that can be executed by the server.
4. Compilation Phase:
The translated servlet code is then compiled into bytecode by the Java
compiler.
The resulting bytecode is loaded by the Java Virtual Machine (JVM) and
executed when the JSP page is requested.
5. Initialization:
6. Request Processing:
When a client request is received for the JSP page, the servlet container
invokes the service() method of the servlet corresponding to the JSP
page.
The service() method processes the request, including executing any Java
code embedded within the JSP page and generating dynamic content.
Java code embedded within the JSP page (such as scriptlets, expression
tags, and custom tags) is executed to generate dynamic content.
8. Response Generation:
9. Client Response:
The client's web browser receives the HTML response from the server and
renders it to the user.
JSP pages can also define lifecycle event methods, such as init() ,
destroy() , service() , etc., similar to servlets.
1. Declarations:
Declarations in JSP are used to declare variables and methods that are accessible
throughout the JSP page. They are typically used to define reusable components
and utility methods. Here's how declarations are used:
Example:
void incrementCount() {
count++;
}
%>
2. Directives:
Directives in JSP provide instructions to the JSP container about how to process
the JSP page. They are used to specify page-level attributes, include other files,
and declare custom tag libraries. Here's how directives are used:
<%@ taglib %> : Declares a custom tag library for use in the JSP page.
Example:
In summary, declarations in JSP are used to declare variables and methods that
can be accessed throughout the JSP page, while directives are used to provide
instructions to the JSP container about how to process the page. By using
declarations and directives effectively, developers can create modular and
maintainable JSP pages that adhere to best practices in JSP development.
Example:
In this example, the value of the username variable is evaluated and inserted
into the HTML output.
2. Code Snippets:
Code snippets in JSP are used to execute Java code within the JSP page. They
are enclosed within
<% %> tags and can include variable declarations, control structures, method calls,
and other Java code. Here's how code snippets are used:
Example:
<%
String username = request.getParameter("username");
if (username != null) {
out.println("Hello, " + username + "!");
}
%>
In this example, we retrieve the value of the username parameter from the
request and output a personalized greeting using the out.println() method.
Expressions are used to embed dynamic content within the HTML markup,
while code snippets are used to execute Java code.
Expressions are evaluated and converted to a string, while code snippets are
executed directly.
It's important to use code snippets judiciously and avoid mixing presentation
logic with business logic in JSP pages to maintain readability and
maintainability.
1. request:
The request object represents the HTTP request made by the client to the
server.
Example usage:
2. response:
Example usage:
response.sendRedirect("newPage.jsp");
3. out:
The out object represents the output stream for writing content to the
client's web browser.
Example usage:
out.println("Hello, world!");
4. session:
The session object represents the HTTP session associated with the
client's request.
Example usage:
session.setAttribute("username", "John");
5. application:
application.setAttribute("counter", 0);
6. page:
Example usage:
pageContext.forward("newPage.jsp");
A Java bean is a Java class that follows specific conventions, including having
a public, no-argument constructor and providing getter and setter methods for
accessing and updating bean properties.
Example:
Beans can be instantiated in JSP pages using the <jsp:useBean> standard action
or using scriptlet code.
Bean properties can be set using the <jsp:setProperty> standard action or using
scriptlet code.
Once instantiated, beans can be used within JSP code to access and
manipulate data.
Example:
By using beans in JSP pages, developers can organize and manage data
effectively, promote code reusability, and separate presentation logic from
business logic, resulting in more maintainable and scalable web applications.
// Default constructor
public Person() {
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
index.jsp:
<!DOCTYPE html>
<html>
<head>
<title>Using Beans in JSP</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<jsp:useBean id="person" class="Person" scope="session"/>
In this example:
We have a Person class with name and age properties along with getter and
setter methods.
Inside the JSP scriptlet ( <% %> ), we set the properties of the person bean using
its setter methods.
We then access the properties of the person bean using expression tags ( <%=
%> ).
Cookies are small pieces of data sent by the server to the client's web
browser and stored locally on the client's machine.
<%
Cookie cookie = new Cookie("username", "john");
cookie.setMaxAge(3600); // Cookie expiration time in s
econds (1 hour)
response.addCookie(cookie);
%>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
String username = cookie.getValue();
Session objects are server-side objects maintained by the web container that
store session-related data for each client session.
Session objects are accessed using the HttpSession interface in Java servlets
and JSP pages.
<%
session.setAttribute("username", "john");
%>
<%
String username = (String) session.getAttribute("usern
ame");
// Use the username...
%>
3. Session Management:
Sessions can be managed using session IDs, which are typically stored in
cookies or appended to URLs.
The session ID uniquely identifies each client session and allows the server to
associate session data with the correct client.
<%
String sessionId = session.getId();
%>
By using cookies and session objects for session tracking, developers can create
stateful web applications that maintain user data and session state across multiple
requests, providing a seamless and personalized user experience. However, it's
essential to consider security implications, such as cookie expiration, session
hijacking, and data privacy, when implementing session tracking mechanisms in
web applications.
Before using JDBC, ensure that the JDBC driver for your specific database is
available in your project. You can typically download the JDBC driver from the
official website of your database vendor and include it in your project's
classpath.
Use the JDBC API to establish a connection to the database. The connection
string contains information such as the database URL, username, and
password.
Once the connection is established, you can create and execute SQL queries
to interact with the database. You can use Statement or PreparedStatement
objects to execute SQL queries.
<%
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT *
FROM users");
while (resultSet.next()) {
String username = resultSet.getString("username");
// Process the retrieved data...
}
resultSet.close();
statement.close();
%>
After executing all necessary SQL queries, it's essential to close the database
connection to release database resources.
<%
connection.close();
5. Error Handling:
<%
try {
// Database operations
} catch (SQLException e) {
// Handle SQL exception
}
%>
By following these steps, you can connect to a database and execute SQL queries
within a JSP page. However, it's essential to note that mixing database access
logic with presentation logic in JSP pages is not considered a best practice. It's
recommended to encapsulate database access code in Java classes (such as
servlets or DAO classes) and use JSP pages solely for presentation purposes.
This approach promotes code separation, maintainability, and security in web
applications.
Mid Sem
difference between figure and img tag
The <figure> and <img> tags are both used in HTML to display images, but they
serve different purposes and are often used together to provide additional context
or captions for images. Here's a breakdown of the differences between the two:
The <img> tag is a standalone element used to embed images into a web
page.
It does not have any content or text associated with it and is self-closing
( <img src="image.jpg" alt="Description"> ).
The alt attribute provides alternative text for the image, which is
displayed if the image cannot be loaded or for accessibility purposes.
The <img> tag is primarily used to display images without any additional
context or description.
2. <figure> Tag:
The <figure> tag is used to encapsulate content that is referenced from the
main content, typically images, illustrations, diagrams, or code snippets.
<figure>
<img src="image.jpg" alt="Description">
<figcaption>A beautiful sunset</figcaption>
</figure>
In this example, the <figure> tag encapsulates the <img> tag and its associated
caption provided by the <figcaption> element. This structure provides a clear
In summary, while the <img> tag is used specifically for embedding images, the
<figure> tag provides a semantic container for images along with associated
the background image should be repeated both horizontally and vertically. Here's
how to use CSS to control image repetition:
2. CSS Syntax:
selector {
background-image: url('image.jpg');
background-repeat: repeat; /* or repeat-x, repeat-y, o
r no-repeat */
}
3. Example:
.container {
background-image: url('background.jpg');
background-repeat: no-repeat; /* Background image will
not repeat */
.tile {
background-image: url('tile.jpg');
background-repeat: repeat-x; /* Background image will
repeat only horizontally */
}
4. Usage Tips:
5. Background Shorthand:
You can also use the background shorthand property to set multiple
background properties, including background-image and background-repeat , in a
single declaration.
.element {
background: url('image.jpg') repeat-x center top; /* B
ackground image repeats horizontally, centered horizontall
y, and aligned to the top */
}
By controlling image repetition with CSS, you can achieve various visual effects
and optimize the presentation of your web page backgrounds. Experiment with
different combinations of background-repeat values to achieve the desired look for
your website.
Objects stored in the page scope are accessible only within the current
JSP page.
The page scope is the default scope for JSP variables declared using the
<%! %> declaration.
Page scope objects are created when the page is initialized and destroyed
when the page is unloaded.
Example:
Objects stored in the request scope are accessible within the current
HTTP request.
Request scope objects are typically used to pass data between different
components (e.g., servlets, JSP pages) during a single request/response
cycle.
Request scope objects are created when the request is received by the
server and destroyed when the response is sent back to the client.
Example:
<%
request.setAttribute("requestScopedAttribute", "Req
Objects stored in the session scope are accessible across multiple HTTP
requests from the same client within the same session.
Session scope objects are often used to maintain user-specific data, such
as user authentication status or user preferences, throughout a user's
session.
Session scope objects are created when the user's session is established
(e.g., after successful login) and destroyed when the session expires or is
invalidated.
Example:
<%
session.setAttribute("sessionScopedAttribute", "Ses
sion scope attribute");
%>
Objects stored in the application scope are accessible to all users and
sessions within the entire web application.
Example:
<%
application.setAttribute("applicationScopedAttribut
Implement the tag's behavior in the doTag() method (for simple tags) or
override the lifecycle methods (e.g., doStartTag() , doEndTag() ) for classic
tags.
package com.example.tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
Create a .tld file to define the custom tag's attributes and behavior.
Specify the tag name, tag class, and other attributes in the TLD file.
Import the custom tag library using the taglib directive at the top of your
JSP page.
Specify the URI defined in the TLD file to identify the tag library.
Example:
Invoke the custom tag using its tag name within your JSP page.
Example:
<custom:customTag/>
Package the custom tag handler class and the TLD file into a JAR file.
Deploy the JAR file to the WEB-INF/lib directory of your web application.
By following these steps, you can create and use custom tags in JSP to
encapsulate reusable functionality and promote code reusability and
maintainability in your web applications.
1. call() Method:
The call() method is used to invoke a function with a specified this value
and optional arguments passed individually.
The thisArg parameter specifies the value of this to be used within the
function.
function greet(name) {
return `Hello, ${name}!`;
}
2. apply() Method:
The thisArg parameter specifies the value of this to be used within the
function.
Example:
3. bind() Method:
The bind() method creates a new function with a specified this value
and, optionally, pre-filled arguments.
Example:
function greet(city) {
return `Hello, ${this.name} from ${city}!`;
}
Unit - 3
Introduction to Server-Side Development with PHP
PHP (Hypertext Preprocessor) is a popular server-side scripting language
designed for web development. Unlike client-side scripts, which run on the user's
browser, server-side scripts run on the web server, generating dynamic content
that is sent to the client. PHP is embedded within HTML and interacts with
databases, making it a powerful tool for creating dynamic and interactive web
pages.
PHP is known for its ease of use, flexibility, and widespread support across
different web servers and operating systems. It is particularly favored for its ability
to seamlessly integrate with databases, most notably MySQL, allowing for the
development of data-driven applications.
Embedded within HTML: PHP code can be directly embedded into HTML,
making it easy to switch between PHP and HTML in the same document.
Server-Side Execution: PHP scripts are executed on the server, and the result
is sent to the client's browser.
Open Source: PHP is free to use and has a large community contributing to its
continuous improvement.
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello, World!";
?>
</body>
</html>
data types including integers, floats, strings, arrays, objects, NULL, and
resources.
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("Alice");
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbnam
e);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
APIs: PHP can be used to create and consume APIs, facilitating data exchange
between different systems.
Advantages of PHP:
Disadvantages of PHP:
Web Server: A server that handles HTTP requests from clients and serves
web pages or data. Common web servers include Apache, Nginx, and
Microsoft IIS.
1. Client Request: A user interacts with a web page and makes a request (e.g.,
submitting a form).
2. Server Processing: The web server receives the request and passes it to the
appropriate server-side script.
5. Client Response: The web server sends the response back to the client's
browser, which displays the content.
Web APIs: Providing data and services to client applications via RESTful or
GraphQL APIs.
Python: Popular for web frameworks such as Django and Flask, known for
clean and readable code.
Java: Often used for enterprise-level applications with frameworks like Spring.
Security Considerations:
Data Validation: Ensuring that user input is properly validated to prevent SQL
injection, XSS, and other attacks.
Server-side development is crucial for building robust, secure, and scalable web
applications. It handles the business logic, data management, and security
features that are essential for modern web applications, ensuring that they
function correctly and efficiently across different user environments.
Receiving HTTP Requests: Web servers listen for incoming HTTP or HTTPS
requests from clients (browsers or other applications). These requests can be
for web pages, images, scripts, or other resources.
Processing Requests:
Routing: Based on the URL and request type, the server routes the request to
the appropriate handler or script. This might involve mapping URLs to specific
files or application logic.
Generating Responses:
Static Content Serving: For static resources like HTML files, images, CSS, and
JavaScript files, the server retrieves the requested file from the filesystem and
sends it to the client.
Managing Connections:
Security:
Error Logging: Capturing and logging errors or exceptions that occur during
request processing to facilitate troubleshooting and maintenance.
Performance Optimization:
Regular Updates: Applying software updates and patches to keep the server
secure and performant.
Apache HTTP Server: One of the oldest and most widely used web servers,
known for its flexibility and extensive module support.
Basic Syntax:
PHP code is enclosed within
<?php and ?> tags. Here’s an example:
<?php
echo "Hello, World!";
?>
Variables:
Variable names are case-sensitive and can contain letters, numbers, and
underscores.
Data Types:
PHP supports several data types:
<?php
$string = "Hello, PHP!";
$integer = 42;
$float = 3.14;
$boolean = true;
$array = array("apple", "banana", "cherry");
?>
Control Structures:
PHP includes common control structures like if-else statements, loops, and switch
cases.
If-Else Statement:
<?php
$number = 10;
if ($number > 0) {
For Loop:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Iteration: " . $i . "<br>";
}
?>
Foreach Loop:
<?php
$fruits = array("apple", "banana", "cherry");
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
Switch Case:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week";
break;
case "Friday":
echo "End of the work week";
break;
Functions:
Functions in PHP are defined using the
function keyword.
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("Alice");
?>
<!DOCTYPE html>
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Hello, " . $name;
}
?>
Connecting to a Database:
PHP can connect to databases like MySQL using extensions such as MySQLi or
PDO. Here’s a simple example using MySQLi:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"].
"<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Error Handling:
PHP provides mechanisms to handle errors gracefully using
try-catch blocks and error reporting functions.
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEP
TION);
echo "Connected successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Summary:
PHP is a powerful language for server-side development, enabling developers to
create dynamic and interactive web applications. With its easy-to-understand
syntax, extensive library of built-in functions, and strong community support, PHP
remains a popular choice for web developers.
1. Decision Making:
<!DOCTYPE html>
<html>
<body>
<?php
$time = date("H");
</body>
</html>
Switch Case:
The
switch statement is used to perform different actions based on different
conditions.
<!DOCTYPE html>
<html>
<body>
<?php
$dayOfWeek = date("l");
</body>
</html>
2. Looping:
While Loop:
The
while loop executes a block of code as long as the specified condition is true.
<?php
$count = 1;
</body>
</html>
Do-While Loop:
The
do-while loop will always execute the block of code once, and then it will repeat
the loop as long as the specified condition is true.
<!DOCTYPE html>
<html>
<body>
<?php
$count = 1;
do {
echo "Count: $count <br>";
$count++;
} while ($count <= 5);
?>
For Loop:
The
for loop is used when you know in advance how many times the script should
run.
<!DOCTYPE html>
<html>
<body>
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i <br>";
}
?>
</body>
</html>
Foreach Loop:
The
foreach loop works only on arrays, and it is used to loop through each key/value
pair in an array.
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = array("Apple", "Banana", "Cherry");
</body>
</html>
Let's see how PHP decision-making and looping can interact with HTML forms.
<!DOCTYPE html>
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$color = htmlspecialchars($_POST['color']);
if (empty($name) || empty($color)) {
echo "Please enter your name and choose a color.";
} else {
echo "Hello, $name!<br>";
echo "Your favorite color is $color.<br>";
</body>
</html>
In this example:
This quick tour shows how PHP integrates with HTML to handle form data, make
decisions, and perform repetitive tasks, forming the backbone of dynamic and
interactive web applications.
Syntax:
if (condition) {
// code to be executed if condition is true
}
Example:
$age = 20;
if ($age >= 18) {
2. if...else Statement:
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example:
$age = 15;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
3. if...elseif...else Statement:
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} elseif (condition2) {
// code to be executed if condition2 is true
} else {
Example:
$score = 75;
if ($score >= 90) {
echo "Grade A";
} elseif ($score >= 80) {
echo "Grade B";
} elseif ($score >= 70) {
echo "Grade C";
} else {
echo "Fail";
}
Syntax:
while (condition) {
// code to be executed
}
Example:
$x = 1;
while ($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
The do...while loop executes a block of code once, then repeats the loop
as long as a specified condition is true.
Syntax:
do {
// code to be executed
} while (condition);
Example:
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
3. for Loop:
Syntax:
Example:
4. foreach Loop:
Example:
These decision-making and looping structures provide control over the flow of
PHP programs, allowing for efficient execution of code and handling of data.
Understanding and using them effectively are essential for PHP development.
PHP code can be embedded within HTML using opening ( <?php ) and
closing ( ?> ) tags.
Example:
<html>
<body>
HTML and PHP code can be mixed within the same file for creating
dynamic content.
Example:
<html>
<body>
<?php
$name = "John";
echo "<h1>Welcome $name</h1>";
?>
</body>
</html>
Example:
<?php
$loggedIn = true;
if ($loggedIn) {
echo "<p>Welcome back, $username!</p>";
} else {
echo "<p>Please log in to access the content.</p>";
}
?>
4. Forms Processing:
Example:
PHP files can be included within HTML using the include or require
statements.
Example:
<html>
<body>
</body>
</html>
HTML code can be included within PHP strings for generating dynamic
HTML content.
Example:
<?php
$message = "<p>Hello, $username!</p>";
By integrating PHP with HTML, developers can create dynamic and interactive
web pages that respond to user input and data changes. This combination is
widely used in web development to create dynamic and data-driven websites and
applications.
Arrays in PHP
Arrays are a fundamental data structure in PHP that allow you to store multiple
values in a single variable. PHP supports both indexed arrays and associative
arrays.
1. Indexed Arrays:
Syntax:
Accessing elements:
2. Associative Arrays:
Syntax:
Accessing elements:
Syntax:
$contacts = array(
array("name" => "John", "phone" => "123456789"),
array("name" => "Jane", "phone" => "987654321")
);
Accessing elements:
4. Array Functions:
PHP provides numerous built-in functions for working with arrays, such as
count() , sort() , array_push() , array_pop() , array_merge() , etc.
Example:
You can use loops like foreach or for to iterate over arrays and access
their elements.
Example:
6. Array Manipulation:
Example:
Arrays are versatile and widely used in PHP for storing and manipulating data.
Understanding how to work with arrays effectively is crucial for PHP developers.
Functions in PHP
Functions in PHP allow you to encapsulate a block of code that can be reused
throughout your program. They enhance code readability, promote code
reusability, and enable modular programming. PHP supports both built-in
functions and user-defined functions.
1. Defining Functions:
Syntax:
Example:
2. Calling Functions:
Syntax:
functionName($argument1, $argument2);
Example:
greet("John");
3. Function Parameters:
Example:
4. Returning Values:
Syntax:
function functionName() {
// function body
Example:
5. Function Scope:
Variables declared inside a function have local scope and are accessible
only within that function.
Variables declared outside any function have global scope and are
accessible throughout the script.
Example:
function test() {
$localVar = "I'm local";
echo $globalVar; // Accessible
echo $localVar; // Accessible
}
6. Built-in Functions:
Example:
Example:
$greet = function($name) {
echo "Hello, $name!";
};
$greet("John");
Functions are fundamental to PHP programming and are used extensively for
organizing code and performing various tasks. Mastering functions is essential for
writing efficient and maintainable PHP code.
1. User-Agent Detection:
PHP can access the User-Agent HTTP header sent by the client's browser
to identify the browser type and version.
Example:
$userAgent = $_SERVER['HTTP_USER_AGENT'];
echo "User-Agent: $userAgent";
PHP libraries like get_browser() can parse the User-Agent string and
provide detailed information about the client's browser.
3. Conditional Rendering:
Example:
$userAgent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($userAgent, 'MSIE') !== false) {
// Internet Explorer-specific content
echo "<p>This website is best viewed in Internet Ex
plorer.</p>";
} else {
// Non-Internet Explorer content
echo "<p>Welcome to our website!</p>";
}
Example:
5. Feature Detection:
Example:
<script>
if (document.addEventListener) {
// Browser supports addEventListener
} else {
// Fallback for older browsers
}
</script>
6. Responsive Design:
Responsive web design techniques using CSS media queries can adapt
the layout of the web page based on the device's screen size, rather than
the browser type.
Example:
Strings in PHP
Strings are sequences of characters, such as letters, numbers, and symbols,
enclosed within single quotes (''), double quotes ("") or heredoc/nowdoc syntax.
PHP provides a variety of functions and features for manipulating and working
with strings efficiently.
Strings can be declared using single quotes (''), double quotes (""),
heredoc syntax, or nowdoc syntax.
Example:
2. Concatenation:
PHP uses the dot (.) operator for concatenating strings together.
Example:
$firstName = 'John';
$lastName = 'Doe';
$fullName = $firstName . ' ' . $lastName;
3. String Interpolation:
Example:
$name = 'John';
echo "Hello, $name!";
4. String Length:
Example:
5. Substring Extraction:
Example:
6. String Manipulation:
Example:
7. String Comparison:
Example:
$str1 = 'apple';
$str2 = 'banana';
echo strcmp($str1, $str2); // Outputs: -1 (str1 is less
than str2)
8. String Searching:
Example:
Create an HTML form using the <form> element, specifying the method
(usually POST or GET) and action (the URL where the form data will be
submitted).
Example:
Use PHP superglobal arrays like $_POST or $_GET to access form data
submitted through POST or GET methods, respectively.
Example ( process_form.php ):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
echo "Hello, $username!";
3. Form Validation:
Validate form input to ensure it meets the required criteria (e.g., non-
empty fields, valid email addresses, numeric values, etc.).
Example:
$username = $_POST["username"];
if (empty($username)) {
echo "Username is required.";
} else {
echo "Hello, $username!";
}
4. Security Considerations:
Example:
$username = htmlspecialchars($_POST["username"]);
After processing form data, it's common to redirect users to another page
to display the results or provide further instructions.
Use the header() function to send an HTTP redirect header to the browser.
Example:
6. Error Handling:
Display error messages inline within the form or on a separate error page.
Example:
if (empty($username)) {
echo "<p style='color: red;'>Username is required.
</p>";
}
By following these steps, you can effectively process form submissions in PHP,
validate user input, and ensure the security and usability of your web applications.
1. Opening a File:
Use the fopen() function to open a file for reading, writing, or appending.
Syntax:
Modes: "r" (read), "w" (write), "a" (append), "r+" (read/write), "w+"
(read/write, creates if not exists), "a+" (read/append).
Use functions like fread() , fgets() , or file() to read content from a file.
Example:
3. Writing to a File:
Example:
4. Appending to a File:
Use the "a" mode or functions like fwrite() with "a" mode to append
content to a file.
Example:
5. Closing a File:
Always close an opened file using the fclose() function to release system
resources.
Example:
fclose($file);
Example:
if (file_exists("filename.txt")) {
// File exists
}
7. Deleting a File:
Use the unlink() function to delete a file from the server's file system.
Example:
unlink("filename.txt");
8. File Permissions:
Ensure that proper file permissions are set to allow PHP scripts to read
from, write to, or execute files.
Example:
9. Error Handling:
Handle errors gracefully using functions like feof() to check for end-of-
file, feof() to check for file errors, and error_get_last() to retrieve the last
error occurred.
Example:
if (feof($file)) {
echo "End of file reached.";
By utilizing these file handling functions and techniques in PHP, developers can
efficiently manipulate files on the server's file system, perform file operations, and
manage file resources effectively.
1. Cookies:
Cookies are small pieces of data stored on the client's browser. They are
sent with every HTTP request to the same domain that set them.
echo $_COOKIE["username"];
2. Sessions:
Sessions are server-side data storage mechanisms that allow storing user-
specific information across multiple HTTP requests.
session_start();
$_SESSION["username"] = "John";
session_start();
echo $_SESSION["username"];
session_start();
session_destroy();
4. Session Security:
6. Session Storage:
Cookies and sessions play crucial roles in web development, enabling stateful
interactions between web servers and clients. Understanding their usage and
implementing security best practices are essential for building secure and user-
friendly web applications.
Unit - 4
PHP and MySQL Integration
PHP and MySQL are commonly used together to create dynamic web applications
that interact with databases. MySQL is a popular relational database management
system, while PHP is a server-side scripting language ideal for web development.
Integrating PHP with MySQL allows developers to create powerful and data-driven
web applications. Here's how PHP and MySQL can be integrated:
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
Example:
Example:
Example:
mysqli_close($conn);
By integrating PHP with MySQL, developers can create dynamic web applications
that interact with databases, retrieve and manipulate data, and provide
personalized user experiences. Understanding how to securely connect to
databases, execute SQL queries, and handle database errors is essential for
building robust and secure web applications.
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
2. Creating a Table:
Use the CREATE TABLE statement to create a new table in the database.
Example:
Example:
Example:
Example:
Example:
Example:
mysqli_close($conn);
These are some of the basic MySQL commands executed using PHP.
Understanding how to interact with a MySQL database using PHP is fundamental
for building dynamic and data-driven web applications.
Syntax:
<?php
$servername = "localhost"; // or IP address of the serv
er
$username = "username"; // MySQL username
$password = "password"; // MySQL password
$database = "dbname"; // Name of the database
if (!$conn) {
die("Connection failed: " . mysqli_connect_error
());
}
echo "Connected successfully";
?>
Replace "dbname" with the name of the MySQL database you want to
connect to.
If the connection fails, terminate the script using die() to prevent further
execution.
Example:
if (!$conn) {
die("Connection failed: " . mysqli_connect_error
());
}
Always close the database connection when it's no longer needed to free
up server resources.
Example:
mysqli_close($conn);
Establishing a connection to the MySQL server is crucial for PHP scripts to interact
with the database effectively. Remember to handle connection errors gracefully
and close the connection when done to ensure efficient resource management.
1. Creating a Database:
Example:
if (!$conn) {
die("Connection failed: " . mysqli_connect_error
());
}
mysqli_close($conn);
?>
Replace "dbname" with the name you want to give to your database.
2. Selecting a Database:
Example:
Replace "dbname" with the name of the database you want to select.
3. Listing Databases:
You can list existing databases using SQL queries or MySQL built-in
functions.
To list the names of tables within a database, you can query the
information_schema.tables table.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
if (!$conn) {
die("Connection failed: " . mysqli_connect_error
());
}
if (!$result) {
die("Error: " . mysqli_error($conn));
}
mysqli_close($conn);
?>
This code retrieves the names of all tables within the specified database
and prints them.
2. Creating a Table:
To create a new table within the selected database, use the CREATE TABLE
statement.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
if (!$conn) {
die("Connection failed: " . mysqli_connect_error
());
}
if (mysqli_query($conn, $sql)) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($con
n);
}
mysqli_close($conn);
?>
This code creates a new table named "users" with three columns: "id"
(auto-incremented primary key), "username" (VARCHAR), and "email"
(VARCHAR).
errors gracefully and close the connection after use to maintain clean code
execution.
1. Inserting Data:
Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
if (!$conn) {
die("Connection failed: " . mysqli_connect_error
());
}
if (mysqli_query($conn, $sql)) {
echo "Data inserted successfully";
} else {
mysqli_close($conn);
?>
This code inserts a new row into the "users" table with values for the
"username" and "email" columns.
2. Altering Tables:
To alter the structure of a table (e.g., add, modify, or drop columns), use
the ALTER TABLE statement.
Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
if (!$conn) {
die("Connection failed: " . mysqli_connect_error
());
}
if (mysqli_query($conn, $sql)) {
echo "Table altered successfully";
} else {
echo "Error altering table: " . mysqli_error($con
mysqli_close($conn);
?>
This code adds a new column named "age" of type INT to the "users"
table.
Inserting data into tables and altering table structures are common tasks in
database management. Ensure that the data you insert complies with the table's
structure and constraints. Handle errors gracefully and close the connection after
use to maintain clean code execution.
1. Select Query:
Use the SELECT statement to retrieve data from one or more tables.
Example:
<?php
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Username: " . $r
ow["username"] . "<br>";
}
} else {
echo "0 results";
This code fetches all rows from the "users" table and prints their "id" and
"username" columns.
2. Insert Query:
Example:
<?php
$sql = "INSERT INTO users (username, email) VALUES ('jo
hn', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con
n);
}
?>
This code inserts a new record into the "users" table with the specified
values for the "username" and "email" columns.
3. Update Query:
Example:
<?php
$sql = "UPDATE users SET email='newemail@example.com' W
HERE username='john'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($con
This code updates the "email" column for the user with the username
"john" in the "users" table.
4. Delete Query:
Example:
<?php
$sql = "DELETE FROM users WHERE username='john'";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($con
n);
}
?>
This code deletes the record for the user with the username "john" from
the "users" table.
1. Deleting a Database:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
if (!$conn) {
die("Connection failed: " . mysqli_connect_error
());
}
if (mysqli_query($conn, $sql)) {
echo "Database deleted successfully";
} else {
echo "Error deleting database: " . mysqli_error($co
nn);
}
mysqli_close($conn);
?>
This code deletes the database named "dbname". Exercise caution as this
action is irreversible.
2. Deleting Data:
Example:
This code deletes the record(s) with the username "john" from the "users"
table.
3. Deleting a Table:
Example:
<?php
$sql = "DROP TABLE users";
if (mysqli_query($conn, $sql)) {
echo "Table deleted successfully";
} else {
echo "Error deleting table: " . mysqli_error($con
n);
}
?>
1. Using PHPMyAdmin:
Data Type Mismatch: Ensure that the data types of your columns match
the values you're inserting or updating.
Empty Result Sets: Queries returning empty result sets may indicate
issues with data or query logic. Verify your data and query conditions.
Break down complex queries into smaller parts and execute them step by
step to isolate issues.
Check database logs for error messages or warnings that may provide
clues about database issues.
Cookies: Cookies are small pieces of data stored in the client's browser.
They can be used to store user preferences, session identifiers, or other
data. However, cookies have size limitations and may pose security risks if
used to store sensitive information.
Local Storage and Session Storage: HTML5 introduced local storage and
session storage, which allow storing larger amounts of data on the client-
3. Hybrid Approaches:
5. Security Considerations:
Effective state management is essential for building robust, scalable, and secure
web applications. Understanding the various state management techniques and
choosing the appropriate approach based on application requirements is key to
developing successful web applications.
1. User Sessions:
2. Data Persistence:
Web applications frequently deal with data that needs to persist across
requests, such as user preferences, shopping cart items, or form input
data.
Without mechanisms for storing and retrieving this data, users would lose
their progress or settings every time they navigate to a new page or
refresh the browser.
Multiple users accessing and modifying the same data simultaneously can
lead to race conditions, data inconsistencies, and performance
4. Complexity of Interactions:
5. Security Risks:
Query strings are added to the end of a URL after the question mark ? .
Each key-value pair is separated by an ampersand & , and the key and
value are separated by an equals sign = .
Example:
<http://example.com/page?name=John&age=30>
In this example, the query string contains two key-value pairs: name=John
and age=30 .
Query strings are often used to pass data from one page to another within
a web application.
<http://example.com/search?q=query>
The search query query is passed to the search results page via the q
Example in PHP:
<?php
$name = $_GET['name'];
$age = $_GET['age'];
echo "Name: $name, Age: $age";
?>
4. Security Considerations:
Validate and sanitize user input to prevent injection attacks and other
security vulnerabilities.
Query strings provide a simple and convenient way to pass information between
different components of a web application. However, they should be used
judiciously, especially when handling sensitive data, to ensure security and
privacy.
URL paths can contain parameters embedded directly within the path
segments.
Example:
<http://example.com/page/parameter1/value1/parameter2/v
alue2>
In this example, parameter1 and parameter2 are placeholders in the URL path,
and their corresponding values are value1 and value2 .
<?php
Route::get('/page/{parameter1}/{parameter2}', function
($parameter1, $parameter2) {
echo "Parameter 1: $parameter1, Parameter 2: $param
eter2";
});
?>
This example defines a route with two URL path parameters ( parameter1
and parameter2 ) and retrieves their values in the route handler function.
Clean, human-readable URLs: URL path parameters can make URLs more
descriptive and user-friendly.
RESTful API design: URL path parameters are commonly used in RESTful
APIs to represent resources and their identifiers.
4. Security Considerations:
URL path parameters are visible to users and should not be used to
transmit sensitive information.
Validate and sanitize URL path parameters to prevent injection attacks and
other security vulnerabilities.
1. Session Management:
Session cookies are typically temporary and expire when the user closes
the browser or logs out of the application.
2. User Authentication:
Secure cookies with the HTTPOnly and Secure flags can help mitigate
security risks associated with storing sensitive authentication data.
Cookies are commonly used for tracking user behavior and preferences
across multiple visits to a website.
Cookies are set and read using HTTP headers in web servers' responses
and requests.
Cookies play a vital role in web application development for maintaining user
sessions, implementing user authentication, and personalizing user experiences.
However, developers must implement cookies responsibly and consider security
implications to protect user privacy and prevent security vulnerabilities.
1. Data Transmission:
2. Data Persistence:
3. Interoperability:
4. Serialization Formats:
5. Security Considerations:
1. Session Concept:
Sessions are identified by unique session IDs, which are usually stored as
cookies on the client's browser or passed in URLs.
2. Session Management:
When a user initiates a session (e.g., by logging in), the application creates
a session object or record on the server to store session data.
4. Session Security:
Use secure cookies with the HTTPOnly and Secure flags to prevent
cookie theft and session hijacking.
Effective session state management is crucial for building secure, scalable, and
user-friendly web applications. By implementing robust session management
practices and leveraging appropriate storage mechanisms, developers can ensure
a seamless and secure user experience throughout the application's lifecycle.
updated: https://yashnote.notion.site/Web-Technologies-
ceda0c4080c848dd82ca8fc660caf1db?pvs=4