Web Fundamentals
HTTP (Hypertext Transfer Protocol)
Definition: Application-layer protocol for distributed, collaborative, hypermedia information systems. Foundation of web communication.
-
Utility: Stateless request/response model between clients (browsers) and servers.
-
Request/Response Model:
-
Request: Client → Server (method, URI, headers, optional body)
-
Response: Server → Client (status code, headers, optional body)
-
-
Common Methods:
| Method | Purpose | Idempotent? | Safe? | |--------|---------|-------------|-------| |
GET| Retrieve data | Yes | Yes | |POST| Submit data (create) | No | No | |PUT| Update resource | Yes | No | |DELETE| Remove resource | Yes | No | |HEAD| Get headers only | Yes | Yes | |OPTIONS| Query server capabilities | Yes | Yes | |TRACE| Loop-back test | Yes | Yes | |CONNECT| Tunnel (HTTPS proxy) | No | No |
[!TIP] Exam Focus: Distinguish
GET(URL-encoded, cacheable, bookmarkable) vsPOST(body, not cacheable, for sensitive data). Idempotent means multiple identical requests have same effect as single request.
Web Design Issues
Key considerations for effective websites:
-
Usability: Intuitive navigation, clear layout, fast loading.
-
Accessibility: WCAG compliance (alt text, ARIA, keyboard nav).
-
Responsive Design: Fluid grids, media queries, mobile-first.
-
Cross-Browser Compatibility: Test on Chrome, Firefox, Safari, Edge.
-
Performance: Optimize images, minify CSS/JS, leverage caching.
-
SEO: Semantic HTML, proper meta tags, clean URLs, mobile-friendly.
Markup Languages
HTML Structure & Elements
-
Basic Structure:
<!DOCTYPE html>,<html>,<head>(meta, title, links),<body>. -
Attributes: Name-value pairs inside start tag (e.g.,
href,src,class,id). -
Semantic HTML5 Tags:
-
<header>: Introductory content. -
<nav>: Navigation links. -
<section>: Thematic grouping. -
<article>: Independent, self-contained content. -
<footer>: Footer for section/page.
-
Page Layout
-
Tables (
<table>): For tabular data only (not layout). -
<div>&<span>:-
<div>: Block-level container for layout. -
<span>: Inline container for text styling.
-
-
Semantic Layout Example:
<header>...</header> <nav>...</nav> <main> <section>...</section> <article>...</article> </main> <footer>...</footer>
Linking
-
Anchor Tag:
<a href="URL">text</a> -
Types:
-
External:
href="https://example.com" -
Internal (same page):
href="#section-id" -
Internal (other page):
href="page.html#section-id" -
Email:
href="mailto:[email protected]?subject=Topic" -
Phone:
href="tel:+1234567890"
-
Lists
| Type | Tag | Use Case | Example |
|---|---|---|---|
| Ordered | <ol> |
Sequence matters | Steps, rankings |
| Unordered | <ul> |
No sequence | Bullet points |
| Definition | <dl> |
Term-description | Glossary |
<ol>
<li>First</li>
<li>Second</li>
</ol>
<ul>
<li>Item A</li>
<li>Item B</li>
</ul>
<dl>
<dt>HTML</dt>
<dd>Markup language</dd>
</dl>
Forms
-
Attributes:
-
action: URL to process form. -
method:GET(default) orPOST. -
enctype: Encoding type (application/x-www-form-urlencoded,multipart/form-datafor file upload).
-
-
Common Input Types:
<input type="text"> <!-- Single-line text --> <input type="password"> <!-- Masked text --> <input type="radio"> <!-- Single choice (same name) --> <input type="checkbox"> <!-- Multiple choices --> <input type="submit"> <!-- Submit button --> <input type="reset"> <!-- Reset form --> <input type="file"> <!-- File upload --> <select>...</select> <!-- Dropdown --> <textarea>...</textarea> <!-- Multi-line text -->
XHTML vs HTML
| Feature | HTML | XHTML |
|---|---|---|
| Syntax | Loose (forgiving) | Strict (XML rules) |
| Tags | Uppercase/lowercase | Lowercase only |
| Empty Elements | <br> |
<br /> (must close) |
| Attributes | Unquoted allowed | Quoted required |
| Nesting | Sometimes improper | Must be proper |
| Root Element | Optional | <html> must contain exactly one |
| MIME Type | text/html |
application/xhtml+xml |
XML (Extensible Markup Language)
Purpose: Store/transport structured data (platform-independent).
-
Well-Formedness Rules:
-
Single root element.
-
Tags properly nested and closed.
-
Case-sensitive.
-
Attribute values quoted.
-
Special characters (
<,>,&) escaped.
-
-
Attributes vs Elements:
-
Elements: Contain data/sub-elements (preferred for complex data).
-
Attributes: Metadata (ID, type) — should not hold content.
-
-
Validation:
-
DTD (Document Type Definition): Defines structure/syntax.
-
XML Schema (XSD): More powerful, XML-based, supports data types.
-
XSLT (Extensible Stylesheet Language Transformations)
Concept: Transform XML documents into other formats (HTML, text, XML).
-
Key Components:
-
Templates (
<xsl:template>): Match XML nodes to transform. -
XPath: Query language to select nodes (
/bookstore/book,//title). -
Output Methods:
html,xml,text.
-
-
Example Flow:
<xsl:template match="/"> <html><body> <xsl:apply-templates select="bookstore/book"/> </body></html> </xsl:template> <xsl:template match="book"> <h2><xsl:value-of select="title"/></h2> </xsl:template>
Cascading Style Sheets (CSS)
Introduction & Advantages
-
Separation: Content (HTML) vs Presentation (CSS).
-
Advantages:
-
Maintainability: Change one file, updates entire site.
-
Reusability: Same class/style across pages.
-
Faster Development: Predefined classes.
-
Accessibility: Different styles for media (print, screen).
-
Reduced File Size: Less HTML clutter.
-
Basic Syntax & Box Model
-
Syntax:
selector { property: value; } -
Box Model: Every element is a rectangular box.
+---------------------------+ | Margin |
| +---------------------+ | | | Border | | | | +---------------+ | | | | | Padding | | | | | | +-----------+ | | | | | | | Content | | | | | | | +-----------+ | | | | | +---------------+ | | | +---------------------+ |
+---------------------------+
- **Total Width** = `width + padding-left + padding-right + border-left + border-right + margin-left + margin-right`.
---
### **Client-Side Scripting (JavaScript)**
#### **Form Elements: Radio Buttons & Checkboxes**
- **Radio Buttons:**
- **Usage:** Single selection from group (same `name`).
- **Property:** `element.checked` (boolean).
- **Event:** `onclick`, `onchange`.
```javascript
// Get selected radio
const gender = document.querySelector('input[name="gender"]:checked').value;
-
Checkboxes:
-
Usage: Multiple selections (different
nameor same with array). -
Property:
element.checked. -
Event:
onchange(recommended).
// Get all checked const hobbies = []; document.querySelectorAll('input[name="hobby"]:checked').forEach(cb => hobbies.push(cb.value)); -
Document Object Model (DOM)
Tree structure: HTML document as nodes (elements, attributes, text).
-
Accessing Elements:
-
getElementById("id")→ single element. -
getElementsByClassName("class")→ live HTMLCollection. -
querySelector("css")→ first matching element. -
querySelectorAll("css")→ static NodeList.
-
-
Manipulation:
-
Content:
element.innerHTML,element.textContent. -
Styles:
element.style.property = "value"(inline),element.classList.add/remove(). -
Attributes:
element.setAttribute(name, value),element.getAttribute(name).
-
-
Event Handling:
element.addEventListener("click", function() { ... });
Server-Side Scripting with PHP
Language Basics
-
Syntax:
<?php ... ?>(or short<? ... ?>if enabled). -
Variables:
$varName(case-sensitive), dynamic typing. -
Data Types: Integer, float, string, boolean, array, object, NULL, resource.
Loop Statements
| Loop | Use Case | Example |
|---|---|---|
for |
Known iterations | for($$\displaystyle i=0; $$i<10; $i++) |
while |
Condition checked first | while($cond) |
do-while |
At least one execution | do {...} while($cond); |
foreach |
Arrays/objects | foreach($arr as $val) or foreach($arr as $key=>$val) |
Object-Oriented Programming (OOP)
-
Class: Blueprint (
class Car { ... }). -
Object: Instance (
$myCar = new Car();). -
Properties: Variables (data).
-
Methods: Functions (behavior).
-
Constructor:
__construct()— runs on object creation. -
Destructor:
__destruct()— runs on object destruction. -
Inheritance:
class Child extends Parent. -
Visibility:
-
public: Accessible everywhere. -
private: Only within class. -
protected: Within class & subclasses.
-
File Handling
-
Functions:
-
fopen($file, $mode)—r,w,a,x. -
fread($handle, $bytes)orfile_get_contents($file). -
fwrite($handle, $data)orfile_put_contents($file, $data). -
fclose($handle).
-
-
Create File:
fopen("file.txt", "w")creates if not exists (truncates).
State Management
| Feature | Session | Cookie |
|---|---|---|
| Storage | Server ($$\displaystyle _SESSION`) | Client browser (` $$_COOKIE) |
|
| Lifetime | Until browser close or session_destroy() |
Set via expire parameter |
| Size Limit | Large (server memory) | 4KB per cookie |
| Security | More secure (data on server) | Less secure (client-side, tamperable) |
| Start | session_start() required |
setcookie() before output |
| Access | $$\displaystyle _SESSION['key']` | ` $$_COOKIE['key'] |
Cookie Syntax:
setcookie("name", "value", time()+3600, "/", "domain.com", true, true);
// Parameters: name, value, expire, path, domain, secure (HTTPS), httponly (JS access)
Database Connectivity (MySQL)
-
MySQLi (Procedural):
$conn = mysqli_connect("localhost", "user", "pass", "db"); $$\displaystyle result = mysqli_query( $$conn, "SELECT * FROM table"); -
MySQLi (OOP):
$conn = new mysqli("localhost", "user", "pass", "db"); $$\displaystyle result = $$conn->query("SELECT * FROM table"); -
PDO:
$dsn = "mysql:host=localhost;dbname=db;charset=utf8mb4"; $$\displaystyle conn = new PDO( $$dsn, "user", "pass"); -
CRUD Operations:
// CREATE (table) $sql = "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))"; $$\displaystyle conn->exec( $$sql); // INSERT $$\displaystyle stmt = $$conn->prepare("INSERT INTO users (name) VALUES (?)"); $$\displaystyle stmt->execute([ $$name]); // SELECT $$\displaystyle stmt = $$conn->query("SELECT * FROM users"); while($$\displaystyle row = $$stmt->fetch()) { ... } // UPDATE $$\displaystyle stmt = $$conn->prepare("UPDATE users SET name=? WHERE id=?"); $$\displaystyle stmt->execute([ $$newName, $id]); // DELETE $$\displaystyle stmt = $$conn->prepare("DELETE FROM users WHERE id=?"); $$\displaystyle stmt->execute([ $$id]);
Security and Data Integrity
SQL Injection
Mechanism: Attacker inserts malicious SQL via input fields, altering query logic.
-
Example: Input:
' OR '1'='1→SELECT * FROM users WHERE user='' OR '1'='1'(returns all rows). -
Impact: Data theft, modification, deletion, admin access.
-
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); // "s" = string -
Input Validation: Whitelist allowed values (e.g.,
filter_var($email, FILTER_VALIDATE_EMAIL)). -
Escaping:
mysqli_real_escape_string()(less preferred, use with prepared statements). -
Least Privilege: DB user with minimal permissions.
-
Other Considerations
-
Cross-Site Scripting (XSS): Inject malicious scripts into data displayed to users.
- Prevention:
htmlspecialchars($output, ENT_QUOTES, 'UTF-8')before output.
- Prevention:
-
Data Integrity Constraints:
-
Primary Key: Unique, not NULL.
-
Foreign Key: Referential integrity.
-
Unique: No duplicates.
-
Check: Custom condition (e.g.,
age > 18). -
Not Null: Mandatory field.
-
[!TIP] Exam Focus: Always use prepared statements for SQL injection prevention. For XSS, escape output based on context (HTML, JS, URL).