UNIT 2: Web Technologies & Server-Side Scripting
1.0 HTML (HyperText Markup Language) Fundamentals
1.1 Page Structure & Layout
-
Basic Document Structure:
<!DOCTYPE html> <html> <head> <title>Page Title</title> <!-- Meta tags, CSS links, scripts --> </head> <body> <!-- Visible content --> </body> </html> -
Layout Techniques:
-
Tables (
<table>): Legacy method for grid-based layout. -
<div>: Generic block-level container for grouping and styling. -
Semantic Elements (HTML5):
<header>,<nav>,<main>,<section>,<article>,<footer>– define meaning and structure.
-
-
Linking:
-
Anchor Tag:
<a href="URL">Link Text</a> -
hrefAttribute: Specifies destination.-
Internal Link:
href="#section-id"(to an anchor/ID on same page). -
External Link:
href="https://example.com".
-
-
Target Attribute:
target="_blank"opens link in new tab/window.
-
[!TIP] Exam Focus: Be prepared to draw a simple page layout using
<div>or semantic tags and explain the purpose of the<head>section.
1.2 HTML Elements & Lists
-
Ordered List (
<ol>): Numbered items.<ol type="1" start="3"> <li>First item</li> </ol>-
type: 1 (numbers), A/a (letters), I/i (roman). -
start: Starting number/letter.
-
-
Unordered List (
<ul>): Bulleted items.typeattribute (disc, circle, square) is deprecated; use CSS. -
Definition List (
<dl>): Name-value pairs.<dl> <dt>Term</dt> <dd>Definition</dd> </dl> -
Nesting: Lists can be nested within
<li>of another list.
[!TIP] Common Pitfall: Forgetting to close
<li>tags properly when nesting can break list rendering.
1.3 HTML Forms & Input Fields
-
<form>Tag:-
action: URL/script to process form data. -
method:GET(appends data to URL, visible, limited length) orPOST(sends in request body, hidden, no size limit).
-
-
Common Input Fields:
| Input Type | Purpose | Key Attributes | | :--- | :--- | :--- | |
text| Single-line text |name,maxlength,size| |password| Masked text |name| |textarea| Multi-line text |name,rows,cols| |select(dropdown) | Choose from options |name,multiple| |radio| Single choice from group |name(same for group),value| |checkbox| Multiple choices |name(same for group),value| |submit| Sends form |value(button text) | |reset| Clears form |value| |button| Generic button |value,type|
2.0 XHTML (Extensible HTML)
2.1 HTML vs. XHTML
| Feature | HTML | XHTML |
|---|---|---|
| Syntax | Looser, forgiving | Strict, XML-based |
| Case Sensitivity | Case-insensitive tags | Case-sensitive (tags/attributes lowercase) |
| Tag Closing | Optional for some (e.g., <p>) |
All tags must be closed (<br />, <img />) |
| Attribute Quoting | Optional in some cases | All attribute values must be quoted |
| Nesting | Can be incorrect | Must be properly nested |
| Document Type | <!DOCTYPE HTML> |
Requires DTD declaration (Strict, Transitional, Frameset) |
-
DTD (Document Type Definition): Defines rules and elements for the document.
-
Strict: Clean, no presentational tags.
-
Transitional: Allows presentational tags for legacy support.
-
Frameset: For documents using frames.
-
3.0 CSS (Cascading Style Sheets)
3.1 Introduction to CSS
-
Purpose: Separates content (HTML) from presentation (styling).
-
Inclusion Methods:
-
Inline:
style="property: value;"in HTML tag (lowest priority, least maintainable). -
Internal/Embedded:
<style> ... </style>block in<head>. -
External:
.cssfile linked via<link rel="stylesheet" href="styles.css">(best for maintainability).
-
3.2 Advantages of CSS
-
Maintainability & Consistency: Change one CSS file to update entire site's look.
-
Reduced HTML Size/Complexity: Styling moved out of HTML markup.
-
Accessibility: Better control over fonts, colors, layouts for assistive tech.
-
Device Adaptability: Media queries enable responsive design for different screens.
-
Precise Control: Fine-grained control over layout (box model), typography, positioning.
[!TIP] Exam Answer Structure: List 4-5 advantages with a brief one-sentence explanation for each.
4.0 Client-Side Scripting: JavaScript
4.1 JavaScript Form Objects
-
Radio Buttons (
<input type="radio">):-
Grouped by
nameattribute; only one selectable per group. -
Access via
document.formName.radioName.valueordocument.formName.radioName[index].checked.
-
-
Check Boxes (
<input type="checkbox">):-
Grouped by
name; multiple selections allowed. -
Check state via
element.checked(returnstrue/false). -
Access values via
document.formName.checkName.value(if checked) or iterate through collection.
-
4.2 Document Object Model (DOM)
-
Concept: Programming interface for HTML/XML documents. Represents page as a hierarchical tree of nodes (elements, attributes, text).
-
Key Points:
-
DOM Tree: Root (
document) →<html>→<head>,<body>→ child elements. -
Accessing Elements:
document.getElementById('id'),document.getElementsByClassName('class'),document.getElementsByTagName('tag'),document.querySelector(). -
Modifying: Change
innerHTML,textContent,style,className, or create/remove nodes (createElement,appendChild,removeChild).
-
[!TIP] Common Pitfall: Confusing
innerHTML(parses HTML) withtextContent(plain text). UsetextContentfor security to avoid XSS.
5.0 Server-Side Scripting: PHP
5.1 PHP Basics & Loops
-
Script Tags:
<?php ... ?>or short tag<? ... ?>(if enabled). -
Loop Statements:
// for for ($$\displaystyle i = 0; $$i < 10; $i++) { ... } // while while ($condition) { ... } // do-while do { ... } while ($condition); // foreach (for arrays) foreach ($array as $value) { ... } foreach ($array as $key => $value) { ... }
5.2 Object-Oriented Programming (OOP) in PHP
-
Class: Blueprint (
class User { ... }). -
Object: Instance (
$user1 = new User();). -
Properties: Variables (
public $name;). -
Methods: Functions (
public function getName() { ... }). -
Constructor:
__construct()– runs on object creation. -
Inheritance:
class Admin extends User { ... }. -
Visibility:
-
public: Accessible everywhere. -
private: Only within class. -
protected: Within class & child classes.
-
5.3 File Handling in PHP
-
Core Functions:
-
fopen($filename, $mode): Opens file/URL. Modes:r,w,a,x,r+, etc. -
fread($handle, $length): Reads binary-safe file. -
fwrite($handle, $string): Writes to file. -
fclose($handle): Closes file. -
file_get_contents($filename): Reads entire file into string. -
file_put_contents($filename, $data): Writes data to file.
-
-
Permissions: Server user (e.g.,
www-data) must have read/write permissions on file/directory. -
Error Handling: Always check if
fopenreturnsfalse(failure).
5.4 PHP & MySQL Database Integration
-
Connectivity String (using
mysqliprocedural):$conn = mysqli_connect("localhost", "username", "password", "database_name"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } -
Executing Queries:
// SELECT $$\displaystyle result = mysqli_query( $$conn, "SELECT * FROM table"); while($$\displaystyle row = mysqli_fetch_assoc( $$result)) { ... } // INSERT $sql = "INSERT INTO table (col1, col2) VALUES ('val1', 'val2')"; mysqli_query($conn, $sql);
5.4.1 PHP Program for Creating a Table
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
$sql = "CREATE TABLE Users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table Users created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
[!TIP] Security Alert: Never use raw user input in SQL queries. Use prepared statements (
mysqli_prepare) to prevent SQL Injection.
6.0 Data Interchange & Transformation
6.1 XML (Extensible Markup Language)
-
Purpose: Platform-independent, text-based format for structuring and transporting data.
-
Attributes (Key Features):
-
Custom Tags: User-defined, descriptive tags (
<book>,<author>). -
Hierarchical Tree Structure: Nested elements (parent-child).
-
Platform Independence: Plain text, parsed by any XML parser.
-
Well-Formed Rules:
-
Single root element.
-
Tags case-sensitive and must be properly nested/closed.
-
Attribute values in quotes.
-
Special characters (
<,>,&) must be escaped (<,>,&).
-
-
-
XML vs HTML: XML is for data description/storage, HTML is for data display. XML is strict; HTML is forgiving.
6.2 XSLT (Extensible Stylesheet Language Transformations)
-
Role: Transforms an XML document into another format (HTML, text, different XML).
-
Components:
-
XSLT Stylesheet: XML file containing templates (
<xsl:template match="...">). -
XPath: Language to navigate/select nodes in XML source document.
-
-
Process: XSLT processor applies templates to source XML nodes to produce output.
<xsl:template match="/"> <html><body> <h2>Books</h2> <xsl:for-each select="catalog/book"> <p><xsl:value-of select="title"/></p> </xsl:for-each> </body></html> </xsl:template>
7.0 Web Protocols & Communication
7.1 HTTP (HyperText Transfer Protocol)
-
Utility: Application-layer protocol for request-response communication between clients (browsers) and servers.
-
Stateless: Each request is independent; server does not retain user session info by default (requires sessions/cookies).
-
Common Methods (Verbs):
| Method | Purpose | Idempotent? | Safe? | | :--- | :--- | :--- | :--- | | GET | Retrieve data | Yes | Yes | | POST | Submit data (create) | No | No | | PUT | Update/replace resource | Yes | No | | DELETE | Remove resource | Yes | No | | HEAD | Get headers only (no body) | Yes | Yes |
-
Headers: Key-value pairs in request/response (e.g.,
Content-Type,Cookie,Set-Cookie,Authorization).
8.0 Web Development Concepts & Issues
8.1 State Management: Sessions vs. Cookies
| Feature | Session | Cookie |
|---|---|---|
| Storage Location | Server (files, database, memory) | Client (browser) |
| Lifetime | Ends when browser closes or after timeout (server-set) | Persists until expiration date (client-side) |
| Capacity | Large (server resources) | Small (~4KB per cookie) |
| Security | More secure (data not exposed to client) | Less secure (stored in plain text, vulnerable to theft) |
| Usage | Sensitive data (user ID, auth tokens) | Non-sensitive preferences (theme, language) |
| PHP Implementation | session_start(); $_SESSION['key']=value; |
setcookie("name", "value", time()+3600); |
[!TIP] Exam Distinction: Session ID is often stored in a cookie (
PHPSESSID), but the actual session data resides on the server.
8.2 Web Design Issues
-
Cross-Browser Compatibility: Test on Chrome, Firefox, Safari, Edge. Use vendor prefixes, feature detection.
-
Accessibility (WCAG): Semantic HTML, ARIA labels, keyboard navigation, color contrast.
-
Responsive Design: Fluid grids, flexible images, CSS media queries (
@media (max-width: 600px) { ... }). -
Performance: Minify CSS/JS, optimize images, use caching, reduce HTTP requests.
-
Security Considerations:
-
XSS (Cross-Site Scripting): Inject malicious scripts. Prevent: Validate/sanitize input, escape output (
htmlspecialchars()). -
CSRF (Cross-Site Request Forgery): Trick user into unwanted action. Prevent: Use anti-CSRF tokens.
-
Injection (SQL, Command): Prevent: Use prepared statements, input validation, least-privilege DB accounts.
-
8.3 Database Bugs & Security
-
Common Vulnerabilities:
-
SQL Injection: Attacker manipulates SQL query via input. Example:
' OR '1'='1. -
Data Truncation: Input longer than column size causes data loss.
-
Race Conditions: Concurrent access leads to inconsistent state (e.g., double booking).
-
-
Debugging & Prevention:
-
Prepared Statements (Parameterized Queries): Separate SQL logic from data.
$$\displaystyle stmt = $$conn->prepare("SELECT * FROM users WHERE email = ?"); $$\displaystyle stmt->bind_param("s", $$email); $stmt->execute(); -
Input Validation: Check type, length, format (e.g.,
filter_var($email, FILTER_VALIDATE_EMAIL)). -
Output Escaping: Contextual escaping (HTML, JS, SQL).
-
Use ORM/Query Builders: Abstraction layer reduces raw SQL.
-
Database Constraints: Use
NOT NULL,UNIQUE, foreign keys.
-
[!CRITICAL] Golden Rule: Never trust user input. Always validate on server-side and use prepared statements for database interaction.