0% found this document useful (0 votes)
22 views34 pages

Web Technology Important Questions

The document provides important questions and answers related to web technology, focusing on HTML, CSS, and web architecture. It covers topics such as CSS types, the CSS Box Model, HTML form creation, block-level vs inline-level elements, and tier architecture. Additionally, it discusses XML, its rules for well-formed documents, and differentiates between XML Schema and DTD.

Uploaded by

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

Web Technology Important Questions

The document provides important questions and answers related to web technology, focusing on HTML, CSS, and web architecture. It covers topics such as CSS types, the CSS Box Model, HTML form creation, block-level vs inline-level elements, and tier architecture. Additionally, it discusses XML, its rules for well-formed documents, and differentiates between XML Schema and DTD.

Uploaded by

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

CREATED BY: AARYAN JHA

Web Technology Important Questions


Unit 1: HTML and CSS

1. What is CSS? Discuss types of CSS with example. CSS (Cascading Style Sheets) is
used for designing layouts with HTML. There are different approaches to style
sheets, including external, internal, and inline.
o Types of CSS:
 External CSS: Styles are defined in an external .css file and linked to
the HTML document. This is good for applying the same style to
multiple pages.
 Internal CSS: Styles are defined within <style> tags in the <head>
section of an HTML document. This is useful for styling a single page.
 Inline CSS: Styles are applied directly to an HTML element using the
style attribute. This is suitable for unique styles for a single element.
2. What is CSS Box Model? Describe its components with example. The CSS Box
Model is a conceptual box that wraps around every HTML element. It consists of
four main components, from the innermost to the outermost:
o Content: The actual content of the element, such as text or images.
o Padding: The space between the content and the border.
o Border: A line that goes around the padding and content.
o Margin: The space outside the border, between the element and other
elements.
o Example (Conceptual): Imagine a paragraph of text. The text itself is the
content. You can add padding around the text, then a border around that
padding, and finally margin to create space between the paragraph and an
adjacent image.
3. Write HTML and CSS code to design your curriculum vitae (CV) using different
HTML elements like table, image, formatting tags, links.

(For your exam, you should be prepared to write a basic structure demonstrating
these elements. Here's a conceptual outline of what you'd include, as direct code
cannot be provided in this format, but the task involves creating HTML forms,
tables, and web pages, designing layouts using CSS, and using HTML lists,
formatting tags, and image maps.)

o HTML Structure:
 Use <h1> for your name, <h2> for sections (e.g., "Education,"
"Experience").
 Use <p> for paragraphs of text.
 Use

<table> for structured data like education history or work


experience, utilizing <tr>, <th>, and <td>.
CREATED BY: AARYAN JHA

 Use

<img> for your profile picture.

 Use

<a> for links to your portfolio, LinkedIn, etc..

 Use formatting tags like

<strong> or <em> for emphasis.

 Use

<ul> or <ol> for lists (e.g., skills, achievements).

o CSS Styling:
 Apply styles to center elements, set font families/sizes, and define
colors.
 Style tables with borders and padding for readability.
 Use CSS for layout (e.g., using

display: flex or grid for sections).

 Position images and control their size.


4. Create a form using HTML to collect user details (name, address, gender, email,
etc.).

(For your exam, be ready to write the HTML code for a form. The task involves
creating HTML forms.)

o HTML Structure:
 Use the <form> tag.
 Use <label> for input fields.
 Use <input type="text"> for name and address.
 Use <input type="email"> for email.
 Use <input type="radio"> for gender selection.
 Use <textarea> for larger text inputs (e.g., address).
 Include a <button type="submit"> to submit the form.
5. What are block-level and inline-level elements? Differentiate with examples.
o Block-level elements:
 Start on a new line and take up the full width available.
 Can contain other block-level elements and inline-level elements.
 Examples:

<div>, <p>, <h1> to <h6>, <ul>, <li>, <table>, <form>.


CREATED BY: AARYAN JHA

o Inline-level elements:
 Do not start on a new line and only take up as much width as
necessary.
 Cannot contain block-level elements.
 Examples:

<span>, <a>, <img>, <strong>, <em>, <input>, <label>.

o Differentiation: The primary difference lies in how they occupy space and
how they can contain other elements. Block-level elements are like
paragraphs or headings, creating distinct blocks, while inline-level elements
are like words within a sentence, flowing with the text.
6. Explain how to create and use image maps (Client-Side and Server-Side). Image
maps allow different parts of an image to be clickable, linking to different
destinations.
o Client-Side Image Maps:
 Processed entirely by the user's browser.
 Created using the

<map> and <area> HTML tags in conjunction with an <img> tag.

 The usemap attribute of the <img> tag points to the name attribute of
the <map> tag.
 <area> tags define clickable regions (rect, circle, poly) with coords
and href attributes.
 Advantage: Faster response time as no server request is needed.
o Server-Side Image Maps:
 Processing occurs on the web server.
 The

<img> tag has an ismap attribute and is placed inside an <a> tag that
points to a server-side script.

 When a user clicks on the image, the browser sends the click
coordinates to the server-side script, which then determines the
appropriate action.
 Disadvantage: Slower response time due to server communication.
7. Describe the structure and attributes of HTML tables, including rowspan and
colspan. HTML tables are used to display tabular data.
o Structure:
 <table>: The root element for a table.
 <thead>: Groups header content in a table (optional).
 <tbody>: Groups the body content in a table (optional).
 <tfoot>: Groups footer content in a table (optional).
 <tr>: Defines a table row.
 <th>: Defines a header cell in a table.
CREATED BY: AARYAN JHA

 <td>: Defines a standard data cell in a table.


o Attributes:
 border: Specifies the width of the table border.
 width: Sets the width of the table.
 cellpadding: Specifies the space between the cell content and its
borders.
 cellspacing: Specifies the space between cells.
 rowspan: An attribute used in <th> or <td> to specify the number of
rows a cell should span.
 Example: <td rowspan="2">This cell spans 2 rows</td>
 colspan: An attribute used in <th> or <td> to specify the number of
columns a cell should span.
 Example: <th colspan="3">This header spans 3
columns</th>
8. Discuss different approaches to style sheets: external, internal, and inline. These are
the three main ways to apply CSS to HTML documents.
o External Style Sheets:
 How: Styles are defined in a separate .css file (e.g., styles.css) and
linked to the HTML document using the <link> tag in the <head>
section: <link rel="stylesheet" href="styles.css">.
 Advantages: Promotes reusability (single CSS file for multiple HTML
pages), easier to maintain, faster page loading (CSS is cached after the
first visit).
 Disadvantages: Requires an extra HTTP request to fetch the CSS file.
o Internal Style Sheets:
 How: Styles are defined within <style> tags placed in the <head>
section of an HTML document.
 Advantages: Useful for applying unique styles to a single HTML page,
no extra HTTP request needed for styles.
 Disadvantages: Not reusable across multiple pages, can make HTML
files larger.
o Inline Style Sheets:
 How: Styles are applied directly to individual HTML elements using
the style attribute.
 Example: <p style="color: blue; font-size: 16px;">This is a
blue paragraph.</p>.
 Advantages: Useful for quick, single-instance style changes, takes
highest precedence.
 Disadvantages: Poor separation of concerns (mixing content and
presentation), hard to maintain, not reusable, makes HTML code
cluttered.

Unit 2: Issues of Web Technology


CREATED BY: AARYAN JHA

1. Explain tier architecture. Differentiate between 2-tier and 3-tier architecture with
examples. Tier architecture refers to the distribution of software components across
different logical layers or physical machines to handle specific functions.
o 2-Tier Architecture:
 Structure: Typically consists of a client tier (presentation layer) and a
server tier (data layer).
 Client Tier: Handles the user interface and business logic.
 Server Tier: Handles data storage and retrieval (e.g., a database
server).
 Interaction: The client directly communicates with the database
server.
 Example: A simple desktop application directly connecting to a
database. In web context, a simple static website directly accessing a
database without an intermediate application server.
 Pros: Simpler to develop for small applications.
 Cons: Limited scalability, poor security (client has direct database
access), difficult to manage logic changes.
o 3-Tier Architecture:
 Structure: Consists of three distinct layers: Presentation Tier,
Application (or Logic) Tier, and Data Tier.
 Presentation Tier (Client): User interface (e.g., web browser).
 Application Tier (Middle Tier): Contains the business logic, processes
requests from the client, and interacts with the data tier. This
separates the client from direct database access.
 Data Tier: Stores and manages data (e.g., database server).
 Interaction: Client interacts with the application tier, which then
interacts with the data tier.
 Example: A typical e-commerce website where the web browser
(presentation) interacts with an application server (e.g., running Java,
Python, or PHP code for business logic), which then communicates
with a database (data).
 Pros: Improved scalability, enhanced security (no direct database
access from client), easier maintenance and development due to
separation of concerns, greater flexibility.
 Cons: More complex to design and implement.
2. Explain multi-tier web architecture with its advantages and disadvantages. Multi-
tier web architecture is an extension of the 3-tier model, involving more than three
layers to distribute various components and functionalities across different servers
or processes. It's a common approach for complex, large-scale web applications.
o Common Tiers (beyond 3-tier):
 Web Server Tier: Handles HTTP requests and serves static content
(e.g., Apache, Nginx).
 Application Server Tier: Executes dynamic content and business logic
(e.g., Tomcat, JBoss, Node.js).
 Database Tier: Stores and manages data (e.g., MySQL, PostgreSQL).
CREATED BY: AARYAN JHA

 Caching Tier: Stores frequently accessed data for faster retrieval (e.g.,
Redis, Memcached).
 Load Balancer Tier: Distributes incoming network traffic across
multiple servers to ensure high availability and responsiveness.
 Security Tier: Firewalls, intrusion detection systems.
o Advantages:
 Scalability: Each tier can be scaled independently, allowing for better
resource allocation. You can add more web servers, application
servers, or database servers as needed.
 Reliability/Availability: Failure in one tier is less likely to bring down
the entire system. Load balancing and redundancy can be easily
implemented.
 Maintainability: Easier to update, modify, or troubleshoot individual
components without affecting the entire application due to clear
separation of concerns.
 Security: Improved security as direct access to sensitive tiers (like the
database) is restricted to specific intermediate tiers.
 Flexibility: Allows for the use of different technologies for different
tiers, optimizing performance for specific tasks.
 Performance: Can improve performance by distributing workload
and optimizing resource usage.
o Disadvantages:
 Complexity: More complex to design, develop, and manage due to
distributed components and inter-tier communication.
 Increased Latency: Communication between multiple tiers can
introduce network latency.
 Cost: Can be more expensive due to the need for more servers and
infrastructure.
 Debugging: Troubleshooting issues can be more challenging due to
the distributed nature of the system.
3. Discuss architectural issues of the web layer. The web layer (often the presentation
tier or the web server aspect of multi-tier architecture) faces several architectural
challenges:
o Scalability: How to handle increasing numbers of concurrent users and
requests without performance degradation. This involves strategies like load
balancing, caching, and horizontal scaling of web servers.
o Performance: Ensuring fast response times for users. Issues include slow
rendering, large asset sizes, unoptimized code, and inefficient server
configurations.
o Security: Protecting against common web vulnerabilities like Cross-Site
Scripting (XSS), SQL Injection, Cross-Site Request Forgery (CSRF), session
hijacking, and denial-of-service (DoS) attacks. Proper input validation,
output encoding, secure session management, and robust
authentication/authorization are critical.
CREATED BY: AARYAN JHA

o Reliability and Availability: Ensuring the web application is consistently


accessible and functional. This involves redundancy, failover mechanisms,
and robust error handling.
o Maintainability and Extensibility: Designing the web layer so it's easy to
update, add new features, and fix bugs without breaking existing
functionality. This often involves modular design, clear code structure, and
good documentation.
o State Management: Handling user sessions effectively, especially in a
stateless protocol like HTTP. This involves using cookies, sessions, or URL
rewriting.
o Browser Compatibility: Ensuring the web application functions correctly
and consistently across different web browsers and devices (responsive
design).
o Caching: Implementing effective caching strategies (browser caching, server-
side caching) to reduce server load and improve performance.
o Load Balancing: Distributing incoming traffic across multiple web servers to
prevent overload and ensure high availability.

Unit 3: The Client Tier (XML, DTD, XSLT)

1. What is XML? Write rules to create a well-formed XML document with example.
XML (Extensible Markup Language) is a markup language designed to store and
transport data. It is self-descriptive and defines a set of rules for encoding
documents in a format that is both human-readable and machine-readable.
o Rules for a Well-Formed XML Document:
1. Root Element: Every XML document must have exactly one root
element.
2. Properly Nested Elements: Elements must be properly nested (e.g.,
<outer><inner></inner></outer> is correct,
<outer><inner></outer></inner> is incorrect).
3. Case-Sensitive Tags: XML tags are case-sensitive (e.g., <book> is
different from <Book>).
4. Closing Tags: Every opening tag must have a corresponding closing
tag, or be an empty-element tag (e.g., <element/>).
5. Valid Characters: Element names and attribute names must follow
XML naming rules (cannot start with xml (case-insensitive), cannot
contain spaces, etc.).
6. Attribute Values in Quotes: All attribute values must be enclosed in
single or double quotes.
7. Prolog (Optional but Recommended): The XML declaration <?xml
version="1.0" encoding="UTF-8"?> is optional but highly
recommended as the first line.
o Example of a Well-Formed XML Document:

XML
CREATED BY: AARYAN JHA
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="101">
<name>John Doe</name>
<major>Computer Science</major>
</student>
<student id="102">
<name>Jane Smith</name>
<major>Electrical Engineering</major>
</student>
</students>

2. Differentiate between XML Schema (XSD) and DTD. Both DTD (Document Type
Definition) and XML Schema (XSD) are used to define the structure and content of
XML documents, but they have key differences.

| Feature | DTD (Document Type Definition) | XML Schema (XSD) |

| | Syntax | Non-XML syntax; uses its own unique syntax. | XML-based syntax; XML
itself. |

| Data Types | Limited basic data types (e.g., PCDATA, CDATA). | Rich set of built-
in data types (e.g., string, integer, boolean, date, time) and allows custom data types.
|

| Namespace | Does not support XML Namespaces. | Fully supports XML


Namespaces. |

| Extensibility | Limited extensibility. | Highly extensible. |

| Readability | Can be less readable due to its unique syntax. | More readable for
XML developers as it uses XML syntax. |

| Validation | Provides basic validation for document structure. | Provides much


stronger validation, including detailed data type constraints and patterns. |

| Ease of Use | Simpler for very basic XML structures. | More complex for simple
structures, but powerful for complex ones. |

| Learning Curve | Quicker to learn for basic use. | Steeper learning curve due to its
extensive features. |

3. Write XML and XSD to store student or visitor information with validations (e.g.,
10-digit phone number, department list).

(For your exam, you should be prepared to write both the XML and XSD. This task
involves creating and validating XML with DTD and XSD.)
CREATED BY: AARYAN JHA

Example XML (student.xml):

XML

<?xml version="1.0" encoding="UTF-8"?>


<students xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="student.xsd">
<student id="S001">
<name>Alice Wonderland</name>
<email>[email protected]</email>
<phone>1234567890</phone>
<department>Computer Science</department>
</student>
<student id="S002">
<name>Bob The Builder</name>
<email>[email protected]</email>
<phone>9876543210</phone>
<department>Electrical Engineering</department>
</student>
</students>

Example XSD (student.xsd):

XML

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="students">
<xs:complexType>
<xs:sequence>
<xs:element name="student" type="studentType"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:complexType name="studentType">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
<xs:element name="phone" type="phoneType"/> <xs:element
name="department" type="departmentType"/> </xs:sequence>
<xs:attribute name="id" type="xs:ID" use="required"/>
</xs:complexType>

<xs:simpleType name="phoneType">
<xs:restriction base="xs:string">
<xs:pattern value="\d{10}"/>
</xs:restriction>
</xs:simpleType>

<xs:simpleType name="departmentType">
<xs:restriction base="xs:string">
<xs:enumeration value="Computer Science"/>
CREATED BY: AARYAN JHA
<xs:enumeration value="Electrical Engineering"/>
<xs:enumeration value="Mechanical Engineering"/>
<xs:enumeration value="Civil Engineering"/>
</xs:restriction>
</xs:simpleType>

</xs:schema>

4. What is XPath? Write an XSLT document to filter and sort XML data. XPath
(XML Path Language) is a language for finding information in an XML document.
It is used to navigate through elements and attributes in an XML document.

XSLT (eXtensible Stylesheet Language Transformations) is a language for


transforming XML documents into other XML documents, or into other formats
such as HTML or plain text. XSLT uses XPath to select parts of the source XML
document.

(For your exam, you should be prepared to write an XSLT document. This task
involves transforming XML using XSLT and using XPath to query XML data.)

Example XML (students.xml):

XML

<?xml version="1.0" encoding="UTF-8"?>


<students>
<student>
<name>Charlie Brown</name>
<age>20</age>
<major>Computer Science</major>
</student>
<student>
<name>David Lee</name>
<age>22</age>
<major>Electrical Engineering</major>
</student>
<student>
<name>Alice Smith</name>
<age>21</age>
<major>Computer Science</major>
</student>
</students>

Example XSLT (filter_sort_students.xsl) to filter for "Computer Science" majors


and sort by name:

XML

<?xml version="1.0" encoding="UTF-8"?>


<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
CREATED BY: AARYAN JHA

<xsl:output method="html" indent="yes"/>

<xsl:template match="/students">
<html>
<head>
<title>Filtered and Sorted Students</title>
</head>
<body>
<h1>Computer Science Students (Sorted by Name)</h1>
<ul>
<xsl:for-each select="student[major = 'Computer
Science']">
<xsl:sort select="name" order="ascending"/>
<li>
<xsl:value-of select="name"/> (<xsl:value-
of select="age"/> years old)
</li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

o Explanation:
 select="student[major = 'Computer Science']": This XPath
expression filters for <student> elements where the child element
major has the text content "Computer Science".
 <xsl:sort select="name" order="ascending"/>: This XSLT
instruction sorts the selected student nodes based on the name element
in ascending alphabetical order.
5. Explain XSL/XSLT and how they are used to transform XML. XSL (eXtensible
Stylesheet Language) is a family of recommendations for transforming and
presenting XML documents. It consists of three parts:
o XSLT (XSL Transformations): Used for transforming XML documents.
o XPath (XML Path Language): Used by XSLT to navigate and select nodes in
an XML document.
o XSL-FO (XSL Formatting Objects): Used for formatting XML documents
for output (e.g., PDF, print).

How XSLT Transforms XML:

XSLT works by applying a stylesheet to an XML source document to produce a


result document. The process involves:

1. Source XML Document: The input XML data that needs to be transformed.
2. XSLT Stylesheet: An XML document containing transformation rules. These
rules are defined using XSLT elements and XPath expressions.
CREATED BY: AARYAN JHA

 Templates (<xsl:template>): Define how specific parts of the source


XML should be transformed. The

match attribute specifies which nodes the template applies to.

 Selection (<xsl:value-of>, <xsl:for-each>): XSLT uses XPath


expressions within these elements to select data from the source XML.
 Output Elements: XSLT can generate new XML, HTML, or plain text
elements in the output based on the transformation rules.
3. XSLT Processor: A software program (e.g., built into web browsers,
programming libraries) that reads the source XML and the XSLT stylesheet,
applies the transformation rules, and generates the output.
4. Result Document: The transformed output, which can be an HTML page,
another XML document, a text file, etc..

In essence, XSLT allows you to convert the structure and content of one XML
document into a completely different structure or format, making XML highly
versatile for data exchange and presentation.

2. Describe the difference between SAX and DOM parsers. SAX (Simple API for
XML) and DOM (Document Object Model) are two common types of parsers used
to process XML documents. They differ fundamentally in how they load and
represent the XML data in memory.

Feature SAX Parser DOM Parser


Parsing Model Event-driven parser. Tree-based parser.
Memory Low memory usage; processes High memory usage; loads the entire
Usage document piece by piece. XML document into memory as a tree
structure.
Data Access Read-only, sequential access. Read-write access; allows navigation
Cannot modify the document. and modification of the document tree.
Processing Faster for large documents as Slower for large documents due to tree
Speed it doesn't build a tree. construction.
Use Cases Best for very large XML files, Best for smaller XML files, when
searching for specific data, random access to data is needed, or
one-pass processing. when modifications are required.
Complexity More complex to implement Easier to use for common tasks, more
for complex navigation. intuitive API.
State Developers must maintain The parser maintains the entire
Management their own state. document's state.

3. Export to Sheets
4. What are order indicators and occurrence indicators in XML Schema? XML
Schema (XSD) uses order indicators and occurrence indicators to define the
expected sequence and number of times child elements can appear within a complex
type.
CREATED BY: AARYAN JHA

o Order Indicators:

These define the allowed order of child elements within a complex type.

 <xs:sequence>: The child elements must appear in the exact order in


which they are declared.
 Example: <xs:sequence><xs:element
name="firstName"/><xs:element
name="lastName"/></xs:sequence> means firstName must
come before lastName.
 <xs:choice>: Only one of the declared child elements can appear.
 Example: <xs:choice><xs:element
name="email"/><xs:element name="phone"/></xs:choice>
means either email OR phone can be present, but not both.
 <xs:all>: All of the declared child elements must appear, but their
order does not matter. Each element can appear only once (implicitly

minOccurs="1" and maxOccurs="1").

 Example: <xs:all><xs:element name="color"/><xs:element


name="size"/></xs:all> means both color and size must be
present, but color can come before size or vice-versa.
o Occurrence Indicators:

These define how many times a particular element or group of elements can
appear. They are attributes applied to <xs:element>, <xs:group>, or
<xs:any>.

 minOccurs: Specifies the minimum number of times an element can


appear. Default is 1.
 Example: <xs:element name="item" type="xs:string"
minOccurs="0"/> means the item element is optional.
 maxOccurs: Specifies the maximum number of times an element can
appear. Default is 1. Can be set to

"unbounded" for an unlimited number of occurrences.

 Example: <xs:element name="addressLine"


type="xs:string" maxOccurs="unbounded"/> means there
can be one or more addressLine elements.
 Common Combinations:
 minOccurs="0" maxOccurs="0": Element is forbidden.
 minOccurs="1" maxOccurs="1": Element must appear exactly
once (default).
 minOccurs="0" maxOccurs="1": Element is optional (appears
zero or one time).
CREATED BY: AARYAN JHA

 minOccurs="1" maxOccurs="unbounded": Element must


appear at least once, and can appear many times.
 minOccurs="0" maxOccurs="unbounded": Element is optional,
and can appear many times.

Unit 4: The Server Tier

1. What is a web server? Explain its main functions with examples. A web server is a
computer program that stores web content (like HTML pages, images, CSS files,
JavaScript files) and delivers it to web browsers or other client applications upon
request. It uses the Hypertext Transfer Protocol (HTTP) to communicate with
clients.
o Main Functions:
1. Serving Static Content: The most basic function. When a browser
requests a static file (e.g., an HTML file, an image, a CSS stylesheet),
the web server locates the file on its storage and sends it back to the
browser.
 Example: A user types www.example.com/index.html into
their browser. The web server receives the request, finds
index.html on its file system, and sends it back to the user's
browser.
2. Handling HTTP Requests and Responses: It constantly listens for
incoming HTTP requests on a specific port (usually 80 for HTTP, 443
for HTTPS). Once a request is received, it processes it and sends back
an HTTP response, which includes the requested content and status
codes (e.g., 200 OK, 404 Not Found).
 Example: A browser sends a GET /image.png HTTP/1.1
request. The server responds with HTTP/1.1 200 OK and the
binary data of image.png.
3. Executing Server-Side Scripts: For dynamic content, web servers
often work with application servers or have built-in modules to
execute server-side scripts (e.g., PHP, Python, Node.js, ASP.NET).
The script generates HTML, which the web server then sends to the
client.
 Example: A user fills out a login form. The web server receives
the form data, passes it to a PHP script. The PHP script
processes the data (e.g., checks credentials against a database),
and generates an HTML response (e.g., a "Welcome" page or
an "Invalid Login" message), which the web server sends back.
4. Security (Basic Level): Web servers provide basic security features
like access control (restricting access to certain directories or files
based on IP address or authentication), and support for HTTPS
(SSL/TLS encryption) to secure data in transit.
 Example: Configuring the web server to only allow access to an
administration panel from specific IP addresses.
CREATED BY: AARYAN JHA

5. Logging: Web servers maintain access logs that record details about
every request, such as the client's IP address, the requested URL, the
time of the request, and the response status. These logs are crucial for
monitoring, debugging, and security analysis.
 Example: An entry in an Apache access log might look like:
192.168.1.1 - - [21/Jul/2025:10:00:00 +0000] "GET
/index.html HTTP/1.1" 200 1234.
2. What is a session? Explain session management with server-side script example. A

session in web technology refers to a period of interaction between a user and a web
application. Since HTTP is a stateless protocol (meaning each request is
independent of the previous one), sessions are crucial for maintaining user state
across multiple page requests. This allows the server to "remember" a user's
activities, such as being logged in, items in a shopping cart, or preferences.

Session Management: Session management is the process of tracking a user's state


across multiple requests by creating and maintaining a unique session for each user.
The most common way to achieve this is by using a

session ID, which is a unique identifier assigned to each session.

o How it works (typical flow):

1. Session Creation: When a user first interacts with the web application
(e.g., logs in), the server generates a unique session ID.
2. Session ID Transmission: This session ID is then sent back to the
client, usually embedded in a cookie. The cookie is stored on the
client's browser.
3. Subsequent Requests: For every subsequent request, the browser
automatically sends the session ID cookie back to the server.
4. Session Data Retrieval: The server uses this session ID to retrieve the
associated session data (stored on the server-side, e.g., in memory, a
file, or a database). This data can include user ID, login status,
shopping cart contents, etc.
5. Session Expiration: Sessions typically have an expiration time (e.g., 30
minutes of inactivity) or can be explicitly destroyed when a user logs
out.

Server-Side Script Example (Conceptual using PHP for illustration):

(This example provides a conceptual overview, as direct runnable code for a specific
language is beyond the scope of this format. The task involves writing server-side
scripts for session handling.)

login.php (Server-side script for login and session creation):


CREATED BY: AARYAN JHA

PHP

<?php
session_start(); // Start the session or resume existing one

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];

// In a real application, you'd validate credentials against a


database
// For demonstration:
if ($username == "user123" && $password == "pass123") {
$_SESSION['loggedin'] = TRUE; // Store login status in
session
$_SESSION['username'] = $username; // Store username in session
$_SESSION['user_id'] = 123; // Store user ID in session

header("Location: dashboard.php"); // Redirect to a protected


page
exit();
} else {
echo "Invalid username or password.";
}
}
?>
<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<form action="login.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

dashboard.php (Protected page using session data):

PHP

<?php
session_start(); // Resume the session

// Check if the user is logged in


if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== TRUE) {
header("Location: login.php"); // Redirect to login if not logged
in
exit();
}
?>
<!DOCTYPE html>
<html>
<head><title>Dashboard</title></head>
CREATED BY: AARYAN JHA
<body>
<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<p>This is your personalized dashboard content.</p>
<a href="logout.php">Logout</a>
</body>
</html>

logout.php (Server-side script for ending session):

PHP

<?php
session_start(); // Start the session to access its data

// Unset all of the session variables


$_SESSION = array(); // Clear session data

// Destroy the session


session_destroy();

// Redirect to login page or home page


header("Location: login.php");
exit();
?>

This example shows how

session_start() initiates/resumes a session, $_SESSION superglobal array stores


data, and session_destroy() terminates it, all crucial for session management.

3. Create a server-side script to store form input into a database.

(For your exam, you should be prepared to outline the steps and show conceptual
code. This task involves writing scripts to insert form data into a database.)

Conceptual Steps (using PHP and MySQL for illustration):

1. HTML Form: Create an HTML form with method="POST" and an action


attribute pointing to your server-side script. Include input fields with name
attributes.

HTML

<form action="process_form.php" method="post">


Name: <input type="text" name="user_name" required><br>
Email: <input type="email" name="user_email" required><br>
Message: <textarea name="user_message"></textarea><br>
<input type="submit" value="Submit">
</form>
CREATED BY: AARYAN JHA

2. Server-Side Script (process_form.php):


 Receive Form Data: Access the submitted form data using the
appropriate superglobal array (e.g., $_POST in PHP, request.form in
Python Flask).
 Database Connection: Establish a connection to your database (e.g.,
MySQL, PostgreSQL, SQLite) using your database credentials.
 Input Validation/Sanitization: Crucial step to prevent security
vulnerabilities like SQL Injection and to ensure data integrity.
Validate data types, lengths, and format. Sanitize inputs to remove
potentially malicious characters.
 Prepare SQL Query: Construct an SQL INSERT query.

Always use prepared statements to safely insert data, as this separates


the SQL logic from the data, preventing SQL injection.

 Execute Query: Execute the prepared statement with the sanitized


form data.
 Error Handling: Implement error handling to catch issues during
database connection or query execution.
 Response: Provide feedback to the user (e.g., "Data saved
successfully!" or an error message). Redirect the user to another page
if necessary.
 Close Connection: Close the database connection.

Conceptual PHP Script (process_form.php):

PHP

<?php
// 1. Database Configuration
$servername = "localhost";
$username = "db_user";
$password = "db_password";
$dbname = "my_database";

// 2. Establish Database Connection


$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); //
}

// 3. Check if form was submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 4. Receive and Sanitize Form Data
$name = htmlspecialchars($_POST['user_name']); // Basic
sanitization
$email = filter_var($_POST['user_email'], FILTER_SANITIZE_EMAIL);
// Specific email sanitization
CREATED BY: AARYAN JHA
$message = htmlspecialchars($_POST['user_message']); //

// 5. Prepare SQL INSERT statement using a prepared statement


(security)
$stmt = $conn->prepare("INSERT INTO users (name, email, message)
VALUES (?, ?, ?)");
if ($stmt === false) {
die("Prepare failed: " . $conn->error); //
}
$stmt->bind_param("sss", $name, $email, $message); // "sss"
indicates three string parameters

// 6. Execute the query


if ($stmt->execute()) {
echo "New record created successfully!"; //
} else {
echo "Error: " . $stmt->error; //
}

$stmt->close(); // Close statement


}

$conn->close(); // 7. Close database connection


?>

2. Explain how to generate dynamic content using server-side scripting. Dynamic


content refers to web page content that is generated or updated in real-time based
on various factors, such as user input, database queries, time of day, or other
external data sources. Server-side scripting is the core mechanism for generating
this content.

How it works:

1. Client Request: A user's browser sends an HTTP request to the web server
for a dynamic page (e.g., products.php, userprofile.asp).
2. Server-Side Script Execution: The web server recognizes that the requested
resource is a server-side script (e.g., PHP, Python, Ruby, Node.js, ASP.NET).
It then passes the request to the appropriate

application server or interpreter for that scripting language.

3. Data Processing: The server-side script executes. During its execution, it can
perform various operations:
 Access Databases: Retrieve data from databases (e.g., product lists,
user profiles, blog posts).
 Process User Input: Handle data submitted through HTML forms
(e.g., login credentials, search queries, contact messages).
 Perform Calculations: Execute business logic, calculations, or data
transformations.
 Interact with External APIs: Fetch data from other web services (e.g.,
weather APIs, payment gateways).
CREATED BY: AARYAN JHA

 Manage Sessions/Cookies: Read or write session data or cookies to


maintain user state.
 File Operations: Read from or write to files on the server.
4. Content Generation: Based on the processed data and logic, the script
constructs the final HTML, CSS, and JavaScript that will be sent to the
client. This might involve embedding data into HTML templates, generating
HTML tables from database results, or creating personalized messages.
5. Response to Client: The generated dynamic HTML (and other assets) is sent
back to the web server, which then delivers it as an HTTP response to the
client's browser.
6. Browser Rendering: The browser receives the HTML and renders the
dynamically generated content to the user.

Examples of Dynamic Content:

o Personalized Greetings: Displaying "Welcome, John Doe!" after a user logs


in.
o Search Results: Generating a list of products based on a user's search query.
o Shopping Cart: Displaying the items a user has added to their cart.
o Blog Posts: Fetching and displaying recent blog entries from a database.
o Weather Forecasts: Showing current weather conditions by fetching data
from an external API.
o User Profile Pages: Displaying different information for each user based on
their stored data.
o Dynamic Menus/Navigation: Menus that change based on user roles or login
status.

Server-side scripting allows web applications to be interactive, data-driven, and


highly personalized, moving beyond static informational websites.

3. What are tag libraries? Explain with examples. Tag libraries (also known as custom
tags or custom tag extensions) are collections of predefined actions (tags) that extend
the functionality of a server-side scripting language or templating engine. They
allow developers to encapsulate complex logic into simple, reusable XML-like tags,
making web page development cleaner, more efficient, and easier to maintain by
separating presentation from business logic.

Instead of embedding large blocks of scripting code directly into HTML, developers
can use a custom tag that performs that complex operation. The server-side
environment (e.g., a JSP container, a templating engine) recognizes these tags and
executes the associated code.

o Key Benefits:
 Separation of Concerns: Helps keep presentation logic (HTML)
distinct from business logic (server-side code).
CREATED BY: AARYAN JHA

 Reusability: Common functionalities can be packaged into reusable


tags.
 Readability: Makes code cleaner and easier to understand for
designers and developers.
 Maintainability: Changes to business logic are contained within the
tag implementation, not scattered across many HTML pages.
o Examples in different technologies:

1. JSP (JavaServer Pages) Standard Tag Library (JSTL): JSTL is a


widely used collection of custom tags that provide core functionalities
like iteration, conditional logic, XML manipulation, and database
access directly within JSP pages, reducing the need for Java scriplets.
 Example (JSTL c:forEach for iteration):

Instead of:

Java

<%
List<String> items = (List<String>)
request.getAttribute("items");
for (String item : items) {
out.println("<li>" + item + "</li>");
}
%>

You use:

Java

<%@ taglib prefix="c"


uri="http://java.sun.com/jsp/jstl/core" %>
<ul>
<c:forEach var="item" items="${items}">
<li><c:out value="${item}"/></li>
</c:forEach>
</ul>

Here, <c:forEach> is a custom tag that iterates over a


collection, making the JSP page much cleaner.

2. Spring Framework's Form Tag Library (for Java/Spring MVC):

Simplifies the creation of HTML forms, binding form fields to model


attributes.

 Example (Spring Form tags):

HTML
CREATED BY: AARYAN JHA
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form" %>
<form:form modelAttribute="user" action="saveUser">
Name: <form:input path="name"/><br/>
Email: <form:input path="email"/><br/>
<input type="submit" value="Save"/>
</form:form>

Here, <form:form> and <form:input> are custom tags that


automatically generate HTML form elements and bind them to
a Java object.

3. Thymeleaf (for Java/Spring MVC, similar concept to tag libraries):

While not strictly "tag libraries" in the JSP sense, modern templating
engines like Thymeleaf use similar concepts by extending HTML with
special attributes that process server-side logic.

 Example (Thymeleaf th:each for iteration):

HTML

<ul xmlns:th="http://www.thymeleaf.org">
<li th:each="item : ${items}"
th:text="${item}"></li>
</ul>

th:each and th:text act like custom directives/tags that


handle iteration and text output.

In essence, tag libraries provide a more structured and manageable way to embed
dynamic behavior into web pages, shifting from imperative scripting directly in
HTML to a more declarative, component-based approach.

2. Explain how error handling is done in server-side scripting. Error handling in


server-side scripting is crucial for creating robust, user-friendly, and secure web
applications. It involves detecting, reporting, and gracefully managing errors and
exceptions that occur during script execution.

Key Aspects of Server-Side Error Handling:

1. Error Reporting and Logging:


 Display Errors (Development vs. Production): During development,
errors are often displayed directly on the screen for immediate
debugging. In production, error display should be disabled for
security reasons (to prevent revealing sensitive information to
attackers) and user experience.
CREATED BY: AARYAN JHA

 Error Logging: Errors should be logged to a file (e.g., a server log,


application log file) or a logging service. This allows developers to
review issues even when they don't crash the application or are not
visible to users.
 Examples:
 PHP: error_reporting(E_ALL);
ini_set('display_errors', 0); ini_set('log_errors',
1); ini_set('error_log', '/path/to/php_errors.log');
 Python (Flask): Use Python's logging module.
2. Exception Handling (Try-Catch Blocks):
 Most modern server-side languages support try-catch blocks (or
similar constructs like try-except in Python). This allows developers
to "try" to execute a block of code and "catch" specific errors or
exceptions that might occur within that block.
 This prevents the application from crashing and allows for specific
recovery actions or custom error messages.
 Example (Conceptual in PHP):

PHP

try {
// Code that might throw an exception (e.g., database
connection, file operation)
$db = new PDO('mysql:host=localhost;dbname=test',
'user', 'wrong_pass');
echo "Database connected!";
} catch (PDOException $e) {
// Catch a specific database exception
error_log("Database Error: " . $e->getMessage()); //
Log the error
echo "An error occurred during database connection.
Please try again later."; // User-friendly message
} catch (Exception $e) {
// Catch any other general exception
error_log("General Error: " . $e->getMessage()); //
echo "An unexpected error occurred.";
}

3. Custom Error Pages:


 Instead of displaying raw error messages, server-side applications can
redirect users to custom, user-friendly error pages (e.g., 404 Not
Found, 500 Internal Server Error). These pages typically include a
polite message and possibly navigation options.
 Configured in web server (e.g., Apache's .htaccess ErrorDocument
404 /404.html) or within the application framework.
4. Input Validation and Sanitization:
 While not strictly "error handling" in terms of runtime exceptions,
robust input validation and sanitization are the first line of defense
against errors caused by invalid or malicious user input.
CREATED BY: AARYAN JHA

 Prevent errors before they happen by ensuring data conforms to


expected formats and ranges.
5. Graceful Degradation:
 Designing the application to gracefully degrade rather than
completely fail. If a non-critical component (e.g., a social media feed)
fails, the main application should still function.
6. Monitoring and Alerts:
 For production systems, integrating with monitoring tools (e.g., New
Relic, Sentry, ELK stack) that can alert developers to errors in real-
time is essential.

By implementing these strategies, server-side scripts can better handle unexpected


situations, provide a better user experience, and allow developers to identify and
resolve issues efficiently.

Unit 5: Advanced Server Side Issues

1. Write a server-side login script using sessions or cookies.

(This question has been largely covered in Unit 4, Q2 for sessions. Here, we'll briefly
recap for sessions and add a conceptual example for cookies. For your exam, you
should be prepared to write a login script using either method.)

Using Sessions (Recap from Unit 4, Q2):

o Mechanism: Server generates a unique session ID, sends it to the client as a


cookie. Server stores user data linked to this ID.
o Login Flow:
1. User submits username/password to login.php.
2. login.php verifies credentials (e.g., against a database).
3. If valid, session_start() is called, and $_SESSION['loggedin'] =
TRUE; (and other user data) is set.
4. User is redirected to a protected page (e.g., dashboard.php).
5. Protected pages check $_SESSION['loggedin'] to ensure the user is
authenticated.
o Logout: session_destroy() clears session data.

Conceptual Login Script using Cookies (PHP for illustration):

While sessions (which often use cookies internally for the session ID) are generally
preferred for security, direct cookies can also store login status. However, storing
sensitive data like username/password directly in cookies is highly discouraged due
to security risks. This example demonstrates storing a login flag or a remember-me
token in a cookie.

login_cookie.php:
CREATED BY: AARYAN JHA

PHP

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$remember_me = isset($_POST['remember_me']);

// Authenticate user (e.g., from a database)


if ($username == "cookieuser" && $password == "cookiepass") {
// Set a cookie for 7 days if "Remember Me" is checked
if ($remember_me) {
$expire_time = time() + (86400 * 7); // 86400 = 1 day
setcookie("user_logged_in", "true", $expire_time, "/"); //
Cookie name, value, expiration, path
setcookie("username_cookie", $username, $expire_time, "/");
//
} else {
// If not "remember me", set a session cookie (browser
session only)
setcookie("user_logged_in", "true", 0, "/"); // 0 means
expires when browser closes
setcookie("username_cookie", $username, 0, "/"); //
}

header("Location: dashboard_cookie.php");
exit();
} else {
echo "Invalid username or password.";
}
}
?>
<!DOCTYPE html>
<html>
<head><title>Login with Cookie</title></head>
<body>
<form action="login_cookie.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="checkbox" name="remember_me"> Remember Me<br>
<input type="submit" value="Login">
</form>
</body>
</html>

dashboard_cookie.php:

PHP

<?php
// Check if the 'user_logged_in' cookie exists and is true
if (!isset($_COOKIE['user_logged_in']) || $_COOKIE['user_logged_in']
!== "true") {
header("Location: login_cookie.php"); // Redirect to login if not
logged in
CREATED BY: AARYAN JHA
exit();
}
$username = isset($_COOKIE['username_cookie']) ?
htmlspecialchars($_COOKIE['username_cookie']) : 'Guest';
?>
<!DOCTYPE html>
<html>
<head><title>Dashboard (Cookie)</title></head>
<body>
<h1>Welcome, <?php echo $username; ?>!</h1>
<p>This is your personalized dashboard content from cookies.</p>
<a href="logout_cookie.php">Logout</a>
</body>
</html>

logout_cookie.php:

PHP

<?php
// Unset/delete cookies by setting their expiration to a past time
setcookie("user_logged_in", "", time() - 3600, "/");
setcookie("username_cookie", "", time() - 3600, "/");

header("Location: login_cookie.php");
exit();
?>

Note: While using cookies directly for simple flags or "remember me" functionality
is common, storing sensitive user data directly in cookies is not recommended due to
client-side accessibility and potential for manipulation. Sessions are generally more
secure for storing user state.

2. Develop a simple web page that takes user input and stores it into a database.

(This question is almost identical to Unit 4, Q3. The solution and explanation
provided there are fully applicable. For your exam, focus on the HTML form,
server-side script logic, database connection, validation, and SQL INSERT query
with prepared statements.)

Refer to Unit 4, Question 3 for the detailed explanation and conceptual code. Key
points for development:

o HTML Form: index.html (or part of a dynamic page) with <form


method="post" action="save_data.php"> and various input fields with
name attributes.
o Server-Side Script (save_data.php):

1. Receive
CREATED BY: AARYAN JHA

$_POST data.

2. Connect to database (e.g., MySQLi or PDO in PHP).


3. Validate and sanitize input (e.g., htmlspecialchars, filter_var,
regex checks).
4. Prepare an SQL

INSERT query using prepared statements (e.g., INSERT INTO users


(name, email) VALUES (?, ?)).

5. Bind parameters and execute the statement.


6. Handle success/failure (e.g.,

echo "Data saved." or redirect).

7. Close database connection.


3. What are cookies? Write a script to set and retrieve cookies.

Cookies are small pieces of data that a server sends to a user's web browser. The
browser stores these cookies and sends them back to the same server with every
subsequent request. They are primarily used to remember stateful information or to
record the user's Browse activity (e.g., login status, shopping cart items, user
preferences, tracking).

o Key Characteristics:
 Small Size: Typically a few kilobytes.
 Domain-Specific: Sent only back to the domain that set them.
 Expiration: Can have an expiration date (persistent cookies) or expire
when the browser closes (session cookies).
 Security Concerns: Can be vulnerable if not handled correctly (e.g.,
storing sensitive data, XSS attacks). HTTPS (Secure flag) and
HttpOnly flag are crucial for security.

Script to Set and Retrieve Cookies (PHP Example):

cookie_example.php:

PHP

<?php
// --- PART 1: Setting a Cookie ---
if (isset($_POST['set_cookie_submit'])) {
$cookie_name = "user_preference";
$cookie_value = "dark_mode";
$expiration_time = time() + (86400 * 30); // Cookie expires in 30
days (86400 seconds = 1 day)

// setcookie(name, value, expire, path, domain, secure, httponly)


CREATED BY: AARYAN JHA
setcookie($cookie_name, $cookie_value, $expiration_time, "/"); //
Sets a persistent cookie
echo "<p>Cookie '{$cookie_name}' set with value '{$cookie_value}'
for 30 days.</p>";
}

// --- PART 2: Setting a Session Cookie ---


if (isset($_POST['set_session_cookie_submit'])) {
$session_cookie_name = "last_visit";
$session_cookie_value = date("Y-m-d H:i:s");

setcookie($session_cookie_name, $session_cookie_value, 0, "/"); //


0 means expires when browser closes
echo "<p>Session cookie '{$session_cookie_name}' set with value
'{$session_cookie_value}'.</p>";
}

// --- PART 3: Retrieving Cookies ---


echo "<h2>Current Cookies:</h2>";
if (isset($_COOKIE["user_preference"])) {
echo "<p>User Preference: " .
htmlspecialchars($_COOKIE["user_preference"]) . "</p>"; //
} else {
echo "<p>Cookie 'user_preference' not set.</p>";
}

if (isset($_COOKIE["last_visit"])) {
echo "<p>Last Visit (Session Cookie): " .
htmlspecialchars($_COOKIE["last_visit"]) . "</p>"; //
} else {
echo "<p>Session cookie 'last_visit' not set.</p>";
}

// --- PART 4: Deleting a Cookie ---


if (isset($_POST['delete_cookie_submit'])) {
// To delete a cookie, set its expiration time to a past value
setcookie("user_preference", "", time() - 3600, "/");
setcookie("last_visit", "", time() - 3600, "/"); // Also delete
session cookie

echo "<p>Cookies 'user_preference' and 'last_visit' have been


deleted.</p>";
// Refresh to see the change
echo "<script>window.location.href =
window.location.href;</script>";
}
?>
<!DOCTYPE html>
<html>
<head><title>Cookie Example</title></head>
<body>
<h2>Set Persistent Cookie</h2>
<form method="post">
<input type="submit" name="set_cookie_submit" value="Set
'user_preference' Cookie">
</form>
CREATED BY: AARYAN JHA
<h2>Set Session Cookie</h2>
<form method="post">
<input type="submit" name="set_session_cookie_submit"
value="Set 'last_visit' Session Cookie">
</form>

<h2>Delete Cookies</h2>
<form method="post">
<input type="submit" name="delete_cookie_submit" value="Delete
All Example Cookies">
</form>
</body>
</html>

o setcookie() function: Used to set a cookie.


 The first parameter is the cookie's name.
 The second is its value.
 The third is the expiration time (Unix timestamp).

time() + (seconds) for persistent, 0 for session-only.

 The fourth is the path (usually / for the entire domain).


o $_COOKIE superglobal array: Used to retrieve cookie values.
4. Write SQL queries for SELECT, INSERT, UPDATE, DELETE.

(For your exam, you should be prepared to write these fundamental SQL
commands. This task involves connecting to databases and executing SQL
commands.)

Assume a table named Employees with columns: EmployeeID (Primary Key, INT),
FirstName (VARCHAR), LastName (VARCHAR), Department (VARCHAR),
Salary (DECIMAL).

1. SELECT (Retrieve Data): Used to retrieve data from one or more tables.
 Select all columns from all rows:

SQL

SELECT * FROM Employees;

 Select specific columns from all rows:

SQL

SELECT FirstName, LastName, Salary FROM Employees;

 Select with a WHERE clause (filtering rows):

SQL
CREATED BY: AARYAN JHA
SELECT FirstName, LastName FROM Employees WHERE Department
= 'Sales';

 Select with ORDER BY (sorting results):

SQL

SELECT FirstName, LastName, Salary FROM Employees ORDER BY


Salary DESC; -- Descending order

 Select with aggregate functions and GROUP BY:

SQL

SELECT Department, AVG(Salary) AS AverageSalary FROM


Employees GROUP BY Department;

2. INSERT (Add New Data): Used to add new rows of data into a table.
 Insert into all columns (values must be in column order):

SQL

INSERT INTO Employees VALUES (101, 'John', 'Doe',


'Marketing', 60000.00);

 Insert into specific columns (recommended):

SQL

INSERT INTO Employees (FirstName, LastName, Department,


Salary)
VALUES ('Jane', 'Smith', 'Sales', 75000.00);

3. UPDATE (Modify Existing Data): Used to modify existing data in one or


more rows.
 Update a single row (using WHERE clause):

SQL

UPDATE Employees
SET Salary = 80000.00
WHERE EmployeeID = 101;

 Update multiple rows (all employees in a department):

SQL

UPDATE Employees
SET Salary = Salary * 1.05 -- Increase salary by 5%
CREATED BY: AARYAN JHA
WHERE Department = 'Sales';


Caution: Always use a WHERE clause with UPDATE unless you intend to
update all rows.
4. DELETE (Remove Data): Used to remove one or more rows from a table.
 Delete a single row (using WHERE clause):

SQL

DELETE FROM Employees WHERE EmployeeID = 102;

 Delete multiple rows (all employees in a department):

SQL

DELETE FROM Employees WHERE Department = 'Marketing';

 Delete all rows from a table (caution!):

SQL

DELETE FROM Employees; -- Removes all data, but keeps table


structure

(Note: TRUNCATE TABLE Employees; is faster for emptying a table but


is DDL, not DML, and cannot be rolled back.)

 Caution: Always use a WHERE clause with DELETE unless you intend to
delete all rows.
2. What is anonymous access? Discuss Integrated Windows Authentication. These are
two different authentication methods for web servers, particularly relevant in
Windows environments like IIS (Internet Information Services).
o Anonymous Access:
 Concept: Allows users to access public areas of a web server or
application without providing any credentials (username or
password). The server treats all anonymous requests as if they came
from a special, built-in anonymous user account (e.g.,

IUSR in IIS).

 How it works: When a web server receives a request for a resource


configured for anonymous access, it does not prompt the user for
credentials. Instead, it uses the anonymous user account configured
on the server to access the requested file or resource.
 Use Cases: Ideal for public websites that don't require user login,
such as static content, marketing sites, public documentation, or the
initial login page of an application.
CREATED BY: AARYAN JHA

 Security: Provides no individual user accountability. Access is based


on the permissions granted to the anonymous user account, not on
specific user identities. It's suitable for content meant for everyone.
o Integrated Windows Authentication (IWA):
 Concept: A robust authentication method primarily used in corporate
intranets or environments where clients and servers are part of the
same Active Directory domain. It leverages the existing Windows
login credentials of the user's computer to authenticate them
seamlessly to web applications.
 How it works:
1. A user attempts to access a resource on a web server
configured for IWA.
2. The web server (e.g., IIS) challenges the client to provide
authentication.
3. The client's browser (e.g., Internet Explorer, Edge, or
configured Chrome/Firefox) automatically sends the user's
Windows login credentials (or a hash of them) to the server
using security protocols like NTLM or Kerberos.
4. The server verifies these credentials against the Active
Directory domain controller.
5. If authentication is successful, the user is granted access
without needing to re-enter their username and password.
 Use Cases: Common for internal company applications, shared file
repositories, and other resources where users already have Windows
domain accounts. It provides single sign-on (SSO) experience within
the corporate network.
 Security: Provides strong, granular security because it authenticates
individual users and their permissions are based on their Active
Directory group memberships and privileges. It offers high
accountability as requests are tied to specific user identities.

Differentiation Summary:

o Anonymous Access: No user login required, everyone is treated as a generic


"anonymous" user. For public content.
o Integrated Windows Authentication: Seamless login for domain-joined users,
leveraging existing Windows credentials. For internal corporate applications
requiring individual user identity.
3. Explain how to handle files and form data in server-side scripting. Server-side
scripting is essential for processing user input from forms and managing files
(uploading, reading, writing) on the server.

1. Handling Form Data:

o HTTP Methods: Forms typically submit data using GET or POST HTTP
methods.
CREATED BY: AARYAN JHA

 GET: Appends form data to the URL as query parameters. Suitable for
simple queries, non-sensitive data, and when users might bookmark
results. Data is visible in the URL and limited in size.
 POST: Sends form data in the body of the HTTP request. Suitable for
sensitive data (passwords), large amounts of data (file uploads), and
data that modifies the server state. Data is not visible in the URL.
o Retrieving Data: Server-side languages provide superglobal arrays or similar
mechanisms to access submitted data.
 PHP: $_GET for GET requests, $_POST for POST requests, and
$_REQUEST for both.
 Python (Flask): request.args for GET, request.form for POST.
 Node.js (Express): req.query for GET, req.body for POST (requires
body-parser middleware).
o Validation and Sanitization: Crucial for security and data integrity.
 Validation: Checking if data meets expected criteria (e.g., email
format, numeric input, required fields).
 Sanitization: Cleaning data to remove potentially harmful characters
or code (e.g., HTML tags to prevent XSS, special characters to
prevent SQL injection).
 Example: htmlspecialchars() in PHP to prevent XSS when
displaying user input. Using prepared statements for database
interactions.
o Processing Data: After retrieval, validation, and sanitization, the data can be
processed:
 Storing in a database.
 Sending emails.
 Generating dynamic content.
 Performing calculations.

2. Handling Files (Uploads, Reading, Writing):

o File Uploads:

1. HTML Form: The <form> tag must have enctype="multipart/form-


data" and an <input type="file"> element.

HTML

<form action="upload.php" method="post"


enctype="multipart/form-data">
Select image to upload:
<input type="file" name="myFile" id="myFile">
<input type="submit" value="Upload File" name="submit">
</form>

2. Server-Side Script:
CREATED BY: AARYAN JHA

 PHP: Uploaded files are available in the $_FILES superglobal


array.
 $_FILES['myFile']['name']: Original file name.
 $_FILES['myFile']['tmp_name']: Temporary location
on server.
 $_FILES['myFile']['size']: Size in bytes.
 $_FILES['myFile']['type']: MIME type.
 $_FILES['myFile']['error']: Error code.
 Validation: Check file type, size, and potential errors before
moving.
 Moving File: Use functions like move_uploaded_file() (PHP)
to move the temporary file to its permanent destination on the
server.
 Security: Never trust client-side file extensions. Generate
unique filenames to prevent overwriting. Store files outside the
web root if possible. Scan for malware.
o Reading Files:
 Server-side scripts can read content from files stored on the server's
file system.
 PHP: file_get_contents(), fopen() with fread(), fgets().
 Python: open('filename', 'r').read().
 Use Cases: Reading configuration files, log files, data files.
o Writing Files:
 Server-side scripts can write data to new or existing files on the
server.
 PHP: file_put_contents(), fopen() with fwrite().
 Python: open('filename', 'w').write('data').
 Use Cases: Generating log files, saving user-generated content (e.g.,
comments, data backups), creating dynamic files.
 Permissions: Server needs appropriate write permissions to the
directories where files are being written.
 Security: Be cautious about writing arbitrary user input directly to
files, especially executable files, to prevent code injection.

Proper handling of form data and files on the server-side involves robust validation,
sanitization, secure storage practices, and appropriate error handling to protect the
application from vulnerabilities and ensure data integrity.

You might also like