UNIT 2: WEB TECHNOLOGIES & SERVER-SIDE SCRIPTING
I. FOUNDATIONS OF THE WEB & MARKUP LANGUAGES
A. Hypertext Transfer Protocol (HTTP)
-
Definition: An application-layer protocol for distributed, collaborative, hypermedia information systems. It is the foundation of data communication for the World Wide Web.
-
Utility: Enables clients (browsers) to request and servers to deliver web resources (HTML pages, images, videos) in a stateless, request-response model.
-
HTTP Request Methods:
| Method | Purpose / Use Case | Idempotent? | | :--- | :--- | :--- | | GET | Retrieve data from the server (e.g., loading a page). Parameters passed in URL query string. | Yes | | POST | Submit data to the server (e.g., form submission, file upload). Data in request body. | No | | PUT | Replace a target resource with the request payload (full update). | Yes | | DELETE | Remove the specified resource. | Yes | | HEAD | Identical to GET but retrieves only headers, no body (for checking resource existence/metadata). | Yes | | PATCH | Apply partial modifications to a resource. | No |
-
Structure of HTTP Messages:
-
Request Line (Client → Server):
METHOD Request-URI HTTP-Version(e.g.,GET /index.html HTTP/1.1) -
Response Status Line (Server → Client):
HTTP-Version Status-Code Reason-Phrase(e.g.,HTTP/1.1 200 OK) -
Headers: Key-value pairs providing metadata (e.g.,
Content-Type,Content-Length,Set-Cookie). -
Body (Optional): The actual payload (HTML, JSON, file data). GET requests typically have no body; POST/PUT often do.
-
Status Code Categories:
-
1xxInformational -
2xxSuccess (e.g.,200 OK,201 Created) -
3xxRedirection (e.g.,301 Moved Permanently,304 Not Modified) -
4xxClient Error (e.g.,400 Bad Request,404 Not Found) -
5xxServer Error (e.g.,500 Internal Server Error)
-
-
B. HTML (HyperText Markup Language)
-
Core Concepts: A markup language used to create and structure content on the web.
-
Element: The fundamental building block (e.g.,
<p>,<div>). -
Tag: The markup syntax that defines an element (
<tag>opening,</tag>closing). -
Attribute: Provides additional information about an element (e.g.,
<img src="photo.jpg" alt="description">). -
Document Structure: Root
<html>element contains<head>(metadata, title, links) and<body>(visible content).
-
-
Page Layout & Linking:
-
<div>: Block-level container for grouping and styling content (layout sections). -
<span>: Inline container for styling a small portion of text. -
<iframe>: Inline Frame; embeds another HTML document within the current page. -
Hyperlinks (
<a>tag): Creates a link to another resource.<a href="https://example.com" target="_blank" title="Visit Example">Link Text</a>-
href: Destination URL. -
target: Where to open link (_self,_blank,_parent,_top).
-
-
-
HTML Lists:
| List Type | Tags | Use Case | | :--- | :--- | :--- | | Ordered List |
<ol>,<li>| Sequence matters (steps, rankings). | | Unordered List |<ul>,<li>| Sequence doesn't matter (bullet points). | | Definition List |<dl>,<dt>(term),<dd>(description) | Name-value pairs (glossary). |- Nested Lists: Lists can be placed inside
<li>elements of another list.
- Nested Lists: Lists can be placed inside
-
HTML Forms (
<form>):-
Purpose: Collect user input and send it to a server for processing.
-
Key Attributes:
-
action: URL where form data is sent. -
method: HTTP method (GETorPOST). -
enctype: Encoding type for form data (application/x-www-form-urlencoded,multipart/form-datafor file uploads).
-
-
Common Form Fields/Input Elements:
| Input Type | Tag & Key Attributes | Description | | :--- | :--- | :--- | | Text |
<input type="text" name="username">| Single-line text. | | Password |<input type="password" name="pwd">| Masked text. | | Textarea |<textarea name="msg" rows="4" cols="50"></textarea>| Multi-line text. | | Radio Buttons |<input type="radio" name="gender" value="male"> Male| Select one option from a set. | | Checkboxes |<input type="checkbox" name="hobby" value="reading"> Reading| Select multiple options. | | Dropdown |<select name="city"><option value="dl">Delhi</option></select>| Select from a list. | | Submit |<input type="submit" value="Send">| Sends form data. | | Reset |<input type="reset" value="Clear">| Clears form fields. |
-
C. XHTML (Extensible HTML)
-
Definition: A reformulation of HTML as an XML application. It combines HTML's expressive power with XML's strict syntax rules.
-
Relationship: XHTML is HTML written in XML syntax. All XHTML documents are well-formed XML documents.
-
Key Differences from HTML:
| Feature | HTML | XHTML | | :--- | :--- | :--- | | Syntax Rules | Lenient (e.g., optional closing tags, case-insensitive tags). | Strict (must be well-formed XML). | | Tag Case | Case-insensitive (
<DIV>=<div>). | Case-sensitive (must be lowercase:<div>). | | Attribute Quoting | Optional (<input type=text>). | Mandatory (<input type="text">). | | Closed Tags | Some tags are "void" (e.g.,<br>,<img>). | All tags must be closed (<br />,<img ... />). | | Nesting | Can be sloppy. | Must be properly nested (no overlapping). | | Document Type | Optional or simple<!DOCTYPE HTML>. | Mandatory DOCTYPE referencing a DTD. | | Special Chars | Can use directly. | Must use entities (&,<,>). |
II. STYLING & PRESENTATION
A. Cascading Style Sheets (CSS)
-
Definition: A style sheet language used to describe the presentation (layout, colors, fonts) of a document written in a markup language like HTML or XML.
-
Purpose: Separates content (HTML) from presentation (CSS), enabling consistent styling across multiple pages.
-
Advantages:
-
Maintainability: Change one CSS file to update the entire site's look.
-
Consistency: Ensures uniform styling.
-
Bandwidth Reduction: External CSS is cached, reducing page size.
-
Accessibility: Allows users to override styles for readability.
-
Device Compatibility: Enables responsive design (media queries).
-
-
Ways to Apply CSS:
-
Inline:
styleattribute on an element (<p style="color:red;">). Highest specificity, least maintainable. -
Internal/Embedded:
<style>block in the HTML<head>. -
External: Linked
.cssfile (<link rel="stylesheet" href="styles.css">). Most efficient and recommended.
-
-
Basic Concepts:
-
Selector: Targets the HTML element to style (e.g.,
p,.class,#id). -
Property: The style attribute to change (e.g.,
color,font-size). -
Value: The setting for the property (e.g.,
red,16px). -
Common Properties:
color,font-family,background-color,margin,padding,border,display.
-
III. CLIENT-SIDE SCRIPTING & DYNAMIC DOCUMENTS
A. JavaScript Fundamentals (Form Objects)
-
Role: Adds interactivity and dynamic behavior to web pages on the client-side (in the browser).
-
Radio Buttons (
type="radio"):-
Property:
checked(Boolean:trueif selected). -
Usage: Grouped by
nameattribute; only one in the group can be selected. -
Event:
onclickoronchangeto detect selection.
// Get value of selected radio button in group 'gender' let gender = document.querySelector('input[name="gender"]:checked').value; -
-
Checkboxes (
type="checkbox"):-
Property:
checked(Boolean). -
Usage: Independent; multiple can be selected.
-
Event:
onclickoronchange.
// Check if a specific checkbox is ticked if (document.getElementById('agree').checked) { // Proceed } -
B. Document Object Model (DOM)
-
Concept: A programming interface (API) for HTML and XML documents. It represents the page as a tree structure of objects (nodes), where each part of the document (elements, attributes, text) is a node.
-
Purpose: Allows languages like JavaScript to dynamically access, modify, and update the content, structure, and styles of a web page after it has loaded.
-
Key Objects & Methods:
-
document: The rootDocumentobject. -
window: The global object, representing the browser window. -
Common Methods:
-
document.getElementById('id'): Returns element with specific ID. -
document.getElementsByClassName('class'): Returns HTMLCollection of elements. -
document.querySelector('css-selector'): Returns first matching element. -
document.createElement('tagName'): Creates a new element node. -
element.appendChild(childNode): Adds a child node to an element. -
element.innerHTML/element.textContent: Gets/sets content. -
element.style.property: Changes inline CSS style.
-
-
IV. DATA REPRESENTATION & TRANSFORMATION
A. XML (Extensible Markup Language)
-
Definition: A meta-markup language for structuring and transporting data in a platform-independent, self-descriptive format.
-
Purpose: Data storage, configuration, and exchange between systems (APIs, web services). Focuses on what data is, not how it looks.
-
Difference from HTML:
-
HTML: Predefined tags for display (presentation-oriented).
-
XML: User-defined tags for data structure (data-oriented).
-
-
Core Attributes/Features:
-
Well-formedness: Must follow basic XML syntax rules (single root, proper nesting, closed tags, quoted attributes, case-sensitive).
-
Validity: Must conform to a defined structure (DTD or XSD Schema).
-
Extensibility: Users can create their own tags and document structures.
-
Self-Descriptive: Tags describe the data they contain.
-
Platform Independence: Plain text format readable by any system.
-
-
Basic Syntax:
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <!-- Comments look like this --> <![CDATA[<special>characters & markup</special>]]> <!-- CDATA Section --> </bookstore>
B. XSLT (Extensible Stylesheet Language Transformations)
-
Definition: A language for transforming XML documents into other formats (HTML, plain text, another XML structure).
-
Primary Role: Separates data (XML) from its presentation (XSLT → HTML) or structure transformation.
-
Key Components:
-
XSLT Stylesheet: An XML document containing transformation rules.
-
Template (
<xsl:template>): Defines how to transform a set of matching nodes. Usesmatchattribute (XPath expression). -
XPath: Language for navigating and selecting nodes in an XML document (used in
match,select). -
<xsl:output>: Specifies the output format (method="html",method="text",method="xml").
-
-
Basic Transformation Concept:
[XML Source Document] + [XSLT Stylesheet] → [XSLT Processor] → [Result Tree (HTML/Text/XML)]Example Snippet:
<xsl:template match="/bookstore"> <html><body> <h2>Book List</h2> <xsl:apply-templates select="book"/> <!-- Process all <book> children --> </body></html> </xsl:template> <xsl:template match="book"> <p><xsl:value-of select="title"/> by <xsl:value-of select="author"/></p> </xsl:template>
V. SERVER-SIDE SCRIPTING WITH PHP
A. PHP Fundamentals & Syntax
-
Model: PHP scripts are executed on the server. The server processes the PHP code, generates plain HTML, and sends the result to the client's browser.
-
Embedding: PHP code is enclosed within
<?php ... ?>tags within an HTML file.<html> <body> <?php echo "Hello, World!"; ?> </body> </html>
B. Control Structures - Loop Statements
| Loop | Syntax | Use Case |
|---|---|---|
for |
for (init; condition; increment) { ... } |
Known number of iterations. |
while |
while (condition) { ... } |
Loop as long as condition is true (check first). |
do-while |
do { ... } while (condition); |
Execute at least once, then check condition. |
foreach |
foreach ($array as $value) { ... }<br>foreach ($array as $key => $value) { ... } |
Iterate over arrays and objects. |
C. Object-Oriented Programming (OOP) in PHP
-
Class: Blueprint/template for creating objects. Defines properties (variables) and methods (functions).
class Car { // Properties public $color; private $engineNo; // Method public function drive() { echo "Vroom!"; } } -
Object: Instance of a class.
$myCar = new Car(); $myCar->color = "Red"; $myCar->drive(); -
Constructor: Special method
__construct()called automatically when an object is created. Used for initialization. -
Access Modifiers:
-
public: Accessible from anywhere. -
private: Accessible only within the class itself. -
protected: Accessible within the class and its subclasses.
-
-
Inheritance: A class (
child) can inherit properties and methods from another class (parent) usingextends. -
Method Overriding: Child class can redefine a method inherited from the parent class.
D. File Handling
-
Concept: A file is a named, persistent collection of data stored on a storage device.
-
Basic Process:
Open → Read/Write → Close. -
Key Functions & Modes:
| Function | Purpose | Common Modes | | :--- | :--- | :--- | |
fopen($filename, $mode)| Opens a file or URL. Returns a file pointer resource. |r(read),w(write, truncate),a(append),x(create, fail if exists),r+(read/write). | |fclose($handle)| Closes an open file pointer. | N/A | |fwrite($handle, $data)| Writes data to an open file. | N/A | |file_put_contents($file, $data)| Convenience function. Writes data to a file (equivalent tofopen+fwrite+fclose). Respects$mode(e.g.,FILE_APPEND). | N/A |
E. PHP & MySQL Database Connectivity
-
Connectivity String (using
mysqliprocedural):$conn = mysqli_connect("localhost", "username", "password", "database_name"); // or $conn = mysqli_connect("host", "user", "pass", "db");- Parameters: Server (often
localhost), Username, Password, Database Name.
- Parameters: Server (often
-
Basic Database Operations:
// 1. Create Table $sql = "CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, email VARCHAR(50) )"; if (mysqli_query($conn, $sql)) { echo "Table created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); } // 2. Execute Queries (SELECT, INSERT, UPDATE, DELETE) using mysqli_query()
F. Sessions vs. Cookies
| Feature | Cookies | Sessions |
|---|---|---|
| Storage Location | Client-side (browser). | Server-side (temporary files or memory). |
| Data Stored | Small amount (typically ~4KB). | Large amount (limited by server resources). |
| Lifetime | Can be persistent (set expiration date) or session-based (deleted on browser close). | Temporary; ends when browser is closed or after server-defined timeout (default ~24 mins). |
| Security | Less secure; stored in plain text on client, vulnerable to tampering/viewing. | More secure; data never leaves the server. Only a session ID (cookie) is sent to client. |
| Usage in PHP | setcookie(name, value, expire, path, domain, secure, httponly); |
session_start();<br>$_SESSION['key'] = 'value'; |
VI. ADVANCED WEB CONCEPTS & ISSUES
A. Web Design Issues
-
Browser Compatibility: Ensuring site works across different browsers (Chrome, Firefox, Safari, Edge) and versions.
-
Accessibility (WCAG): Designing for users with disabilities (screen readers, keyboard navigation, color contrast, semantic HTML).
-
Responsive Design: Creating layouts that adapt to different screen sizes (desktop, tablet, mobile) using fluid grids, flexible images, and CSS media queries.
-
Performance Optimization: Minimizing HTTP requests, optimizing images, minifying CSS/JS, leveraging caching, using CDNs.
-
Navigation: Intuitive, consistent, and clear site structure with easy-to-find menus and links.
-
Scalability: Designing architecture to handle growth in traffic and content.
-
Security: Protecting against common vulnerabilities (XSS, CSRF, SQL Injection) via input validation, prepared statements, HTTPS, etc.
B. Database Bugs (in Web Context)
-
SQL Injection: Malicious SQL code inserted via user input. Mitigation: Use prepared statements with parameterized queries (e.g.,
mysqli_stmt_prepare). -
Race Conditions: Concurrent access leads to inconsistent data (e.g., double-spending). Mitigation: Use database transactions (
BEGIN,COMMIT,ROLLBACK) and proper locking. -
Data Integrity Violations: Invalid data due to missing constraints. Mitigation: Define PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL constraints.
-
Connection Leaks: Failing to close database connections, exhausting pool. Mitigation: Always
mysqli_close($conn)or use connection pooling; ensure connections are closed in all code paths (including error handling). -
Inefficient Queries: Slow performance due to full table scans, missing indexes. Mitigation: Use
EXPLAINto analyze queries, add appropriate INDEXES onWHERE,JOIN,ORDER BYcolumns.