Skip to content
CY-603 (C) · Autometa & Compiler design/Quick Revision Short Notes

Autometa & Compiler design (CY-603 (C)) - Unit 1 Short Notes

1.0 Introduction to Web Technologies & Markup

1.1 HTML Fundamentals

1.1.1 Page Layout and Structure

HTML5 provides semantic elements for structured, accessible page layouts:

  • <header>: Introductory content or navigation aids.

  • <nav>: Navigation links container.

  • <main>: Dominant content of the document.

  • <article>: Independent, self-contained composition.

  • <section>: Thematic grouping of content.

  • <aside>: Tangentially related content (e.g., sidebar).

  • <footer>: Footer for its nearest sectioning element.

Layout is achieved via CSS (Flexbox, Grid, floats). Semantic tags improve SEO and accessibility.

[!TIP] Exam often requires drawing a simple page layout using these tags. Remember the hierarchy: <header>/<nav> → <main> → <article>/<section>/<aside> → <footer>.

1.1.2 Creating Lists

HTML supports three list types:

  1. Ordered List (<ol>): Sequential items (numbered/lettered).

    
    <ol type="1">
    
      <li>First</li>
    
      <li>Second</li>
    
    </ol>
    
    
  2. Unordered List (<ul>): Bulleted items.

    
    <ul style="list-style-type: disc;">
    
      <li>Item A</li>
    
      <li>Item B</li>
    
    </ul>
    
    
  3. Definition List (<dl>): Terms and definitions.

    
    <dl>
    
      <dt>HTML</dt>
    
      <dd>HyperText Markup Language</dd>
    
    </dl>
    
    

[!TIP] <li> must be nested within <ol> or <ul>. For definition lists, use <dt> (term) and <dd> (definition).

1.1.3 HTML Forms and Form Fields

Forms collect user input via <form> element. Key attributes: action (submission URL), method (GET/POST).

Common fields:

  • Text/Password: <input type="text|password">

  • Radio Buttons: <input type="radio" name="group"> (mutually exclusive).

  • Checkboxes: <input type="checkbox" name="hobbies[]"> (multiple selection).

  • Dropdown: <select><option>...</option></select>

  • Textarea: <textarea rows="4" cols="50">

  • Submit: <input type="submit"> or <button type="submit">

[!TIP] Radio buttons share the same name attribute to enforce single selection. Checkboxes can share a name (as array) or have unique names.

1.2 HTML vs. XHTML

1.2.1 Key Differences in Elements, Syntax, and Rules
Aspect HTML XHTML
Syntax Looser; tags/attributes can be uppercase, unquoted attributes, optional closing tags. Strict XML; all lowercase, attributes quoted, all elements must be closed.
Empty Elements <br>, <img> (no closing slash required). Must self-close: <br/>, <img/>.
Document Structure Optional <html>, <head>, <body>. Mandatory root <html> with <head> and <body>.
Error Handling Browsers parse malformed markup. XML parsers are strict; errors break rendering.
MIME Type text/html application/xhtml+xml (or text/html for compatibility).

[!TIP] XHTML is HTML reformulated as XML. Key rule: every opening tag must have a closing tag (or be self-closing) and all attributes must be quoted.


2.0 Styling and Presentation

2.1 Cascading Style Sheets (CSS)

2.1.1 Definition, Purpose, and Core Concepts

CSS is a style sheet language for describing the presentation of HTML/XML documents.

Purpose: Separate content (HTML) from presentation (CSS) for maintainability, accessibility, and flexibility.

Core Concepts:

  • Selectors: Target elements (e.g., p, .class, #id, [attr]).

  • Properties/Values: color: red;, font-size: 16px;.

  • Cascading: Conflicts resolved by specificity, importance (!important), and source order.

  • Inheritance: Some properties (e.g., color) pass from parent to child.

  • Box Model: Each element is a box (content, padding, border, margin).

CSS application methods:

  1. Inline: style="..." attribute.

  2. Internal: <style> block in <head>.

  3. External: Linked via <link rel="stylesheet" href="..."> (recommended).

2.1.2 Advantages of Using CSS
  1. Separation of Concerns: Cleaner HTML, easier maintenance.

  2. Consistency: Single stylesheet controls site-wide appearance.

  3. Bandwidth Reduction: External CSS cached by browser.

  4. Accessibility: Different styles for print/screen, user-overridable.

  5. Flexibility: Multiple stylesheets (e.g., themes) per document.

  6. Device Independence: Media queries for responsive design.

[!TIP] CSS follows the cascade: importance → origin (user agent/user/author) → specificity → order. Use external CSS for production.


3.0 Client-Side Scripting & Interactivity

3.1 JavaScript Fundamentals

3.1.1 Form Input Objects: Radio Buttons and Checkboxes

JavaScript accesses form elements via the DOM.

Radio Buttons (<input type="radio">):

  • Mutually exclusive within same name group.

  • Properties: checked (boolean), value.

  • Get selected value:

    
    const gender = document.querySelector('input[name="gender"]:checked').value;
    
    

Checkboxes (<input type="checkbox">):

  • Independent selection; multiple can be checked.

  • Properties: checked, value.

  • Get all checked in a group:

    
    const hobbies = document.querySelectorAll('input[name="hobbies"]:checked');
    
    hobbies.forEach(cb => console.log(cb.value));
    
    

[!TIP] For radio groups, always check if a button is selected (:checked) before accessing .value to avoid errors.

3.2 Document Object Model (DOM)

3.2.1 Concept, Structure, and Role in Dynamic Web Pages

The DOM is a tree-like, language-agnostic representation of an HTML/XML document, where each node is an object.

Structure:

  • Root: document object.

  • Nodes: element nodes (<div>), text nodes (text content), attribute nodes.

  • Parent-child-sibling relationships.

Role in Dynamic Web Pages:

  • JavaScript uses DOM API to:

    • Traverse: getElementById(), querySelector().

    • Modify: Change content (innerHTML), attributes, styles.

    • Create/Remove: createElement(), appendChild(), removeChild().

    • React to Events: addEventListener() for clicks, keypresses.

Example:


document.getElementById("demo").innerHTML = "Updated!";

[!TIP] The DOM is not part of JavaScript; it's a standard API implemented by browsers. Changes via DOM are in-memory until persisted (e.g., via server requests).


4.0 Server-Side Scripting with PHP

4.1 PHP Basics & Control Structures

4.1.1 Loop Statements
Loop Syntax Use Case
for for ($$\displaystyle i=0; $$i<10; $i++) { ... } Known iteration count.
while while ($$\displaystyle i<10) { ... $$i++; } Condition checked before each iteration.
do-while do { ... } while ($i<10); Execute at least once.
foreach foreach ($arr as $val) { ... } Iterate arrays/objects.

[!TIP] foreach is safest for arrays (avoids off-by-one errors). for is best when index is needed.

4.2 Object-Oriented Programming in PHP

4.2.1 Core OOP Concepts: Classes, Objects, Properties, Methods
  • Class: Blueprint defined by class keyword.

    
    class Car {
    
        public $color;       // Property
    
        private $model;      // Private property
    
        public function setModel($m) { // Method
    
            $$\displaystyle this->model = $$m;
    
        }
    
    }
    
    
  • Object: Instance created via new.

    
    $myCar = new Car();
    
    $myCar->color = "red";
    
    $myCar->setModel("Toyota");
    
    
  • Properties: Variables holding object state. Visibility: public, private, protected.

  • Methods: Functions defining behavior. $this refers to current object.

  • Constructor: __construct() for initialization.

  • Inheritance: class Sedan extends Car { ... }

[!TIP] Use private for internal state, public for interface. Always validate inputs in setters.

4.3 File Handling in PHP

4.3.1 What is a File?

A named collection of data stored on a storage device. In PHP, files are handled via streams and filesystem functions.

4.3.2 Creating, Opening, Reading, Writing
  • Open/Create: fopen("file.txt", "mode")

    • Modes: r (read), w (write/truncate), a (append), x (create new), r+ (read/write).
  • Write: fwrite($handle, "data") or file_put_contents("file.txt", "data").

  • Read: fread($handle, length), fgets() (line), file_get_contents() (whole file).

  • Close: fclose($handle).

  • Check existence: file_exists("file.txt").

Example:

$file = fopen("data.txt", "w") or die("Unable to open file!");

fwrite($file, "Hello World.");

fclose($file);

[!TIP] Always check fopen() success and use fclose() to release resources. Prefer file_put_contents() for simple writes.

4.4 PHP & Database Connectivity (MySQL)

4.4.1 Database Connectivity String/Connection Establishment

Using MySQLi (object-oriented):

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

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

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

The "connectivity string" comprises $servername, $username, $password, $dbname.

4.4.2 Executing SQL Commands: Creating Tables
$sql = "CREATE TABLE users (

    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(50) NOT NULL,

    email VARCHAR(100),

    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP

)";

if ($$\displaystyle conn->query( $$sql) === TRUE) {

    echo "Table created successfully";

} else {

    echo "Error: " . $conn->error;

}
$conn->close();

[!TIP] Never concatenate user input into SQL. Use prepared statements ($conn->prepare()) to prevent SQL injection.


5.0 Data Interchange & Transformation

5.1 Extensible Markup Language (XML)

5.1.1 What is XML?

XML (Extensible Markup Language) is a flexible, text-based format for structured data storage and exchange.

Purpose:

  • Platform-independent data representation.

  • Configuration files (e.g., web.xml, pom.xml).

  • Web services (SOAP, REST with XML payloads).

  • Document formats (e.g., DOCX, SVG).

Well-Formedness Rules:

  1. Single root element.

  2. All tags properly nested and closed (<tag></tag> or <tag/>).

  3. Case-sensitive (<Item> ≠ <item>).

  4. Attribute values quoted (attr="value").

  5. Special characters escaped (&lt;, &amp;).

Example:


<?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>

  </book>

</bookstore>

5.1.2 Attributes of XML

Syntax: name="value" inside start tag.


<book id="123" available="yes">...</book>

Rules:

  • Attribute names are case-sensitive.

  • Values must be quoted (single or double).

  • No duplicate attributes in same element.

  • Cannot contain multiple values (unlike child elements).

Attributes vs. Elements:

Attributes Elements
Simple metadata (ID, flag, single value). Complex, structured data (can nest).
Not extensible (cannot add sub-properties). Extensible; can contain other elements.
Order not significant. Order may be significant.
Example: <person id="1" gender="M"> Example: <person><id>1</id><gender>M</gender></person>

[!TIP] Use elements for data that may need future extension or structure. Use attributes for metadata or non-repeating simple properties.

5.2 XSL Transformations (XSLT)

5.2.1 Purpose and Basic Concept of Transforming XML Data

XSLT (Extensible Stylesheet Language Transformations) converts XML into other formats (HTML, text, XML) using a stylesheet.

Purpose:

  • Present XML data as HTML for browsers.

  • Restructure XML (reorder, filter, aggregate).

  • Generate multiple output formats from same XML.

Basic Concept:

  • XPath: Navigate and select nodes in XML source.

  • Templates: <xsl:template match="pattern"> defines transformation rules.

  • Processor: Applies stylesheet to source XML to produce result tree.

Example stylesheet (XML → HTML table):


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

  <xsl:template match="/">

    <html><body>

      <h2>Books</h2>

      <table border="1">

        <tr><th>Title</th><th>Author</th></tr>

        <xsl:for-each select="bookstore/book">

          <tr>

            <td><xsl:value-of select="title"/></td>

            <td><xsl:value-of select="author"/></td>

          </tr>

        </xsl:for-each>

      </table>

    </body></html>

  </xsl:template>

</xsl:stylesheet>

[!TIP] XSLT is declarative (what to transform) not procedural (how). The match attribute uses XPath expressions to select nodes.


6.0 Web Application Concepts & State Management

6.1 HTTP Protocol

6.1.1 What is HTTP?

HTTP (Hypertext Transfer Protocol) is a stateless, application-layer protocol for client-server communication on the web.

Request-Response Model:

  1. Client Request:

    
    GET /index.html HTTP/1.1\r\n
    
    Host: www.example.com\r\n
    
    [Headers]\r\n\r\n
    
    [Body (for POST/PUT)]
    
    
  2. Server Response:

    
    HTTP/1.1 200 OK\r\n
    
    Content-Type: text/html\r\n
    
    [Headers]\r\n\r\n
    
    [Body (HTML content)]
    
    
6.1.2 HTTP Methods and Their Utility
Method Idempotent? Safe? Purpose
GET Yes Yes Retrieve data (parameters in URL query string). Cacheable, bookmarkable.
POST No No Submit data (e.g., forms). Parameters in body. Not cacheable by default.
PUT Yes No Replace entire resource at given URL.
DELETE Yes No Remove specified resource.
HEAD Yes Yes Same as GET but without response body (fetch headers only).
PATCH No No Partial update of a resource.

Utility:

  • GET for safe, read-only operations (search, navigation).

  • POST for non-idempotent actions (login, create order).

  • PUT/DELETE for RESTful APIs (update/delete resources).

  • HEAD for checking resource existence/last-modified.

[!TIP] GET parameters appear in URL (visible, limited length, cacheable). POST data in body (more secure for sensitive data, larger payload).

6.2 State Management Techniques

6.2.1 Sessions
  • Concept: Server-side storage of user data across multiple requests.

  • Mechanism:

    1. Server creates unique session ID (stored in PHPSESSID cookie by default).

    2. Data stored in $_SESSION superglobal (on server, typically files).

    3. Session ID sent with each request (cookie or URL rewriting).

  • Use-Cases: User authentication, shopping carts, user preferences.

  • PHP Example:

    
    session_start();
    
    $_SESSION["user_id"] = 123;
    
    echo $_SESSION["user_id"];
    
    
6.2.2 Cookies
  • Concept: Client-side key-value pairs stored in browser, sent with each request.

  • Mechanism:

    1. Server sends Set-Cookie: name=value; expires=...; path=/ header.

    2. Browser stores cookie and includes Cookie: name=value in subsequent requests.

    3. Attributes: expires (persistent vs. session), path, domain, secure (HTTPS only), HttpOnly (not accessible via JavaScript).

  • Use-Cases: Remembering language preference, tracking (analytics), non-sensitive tokens.

  • PHP Example:

    
    setcookie("theme", "dark", time() + 3600, "/");
    
    echo $_COOKIE["theme"];
    
    
6.2.3 Differentiating Sessions and Cookies
Feature Sessions Cookies
Storage Location Server (files, DB, memory). Client browser (limited to ~4KB per domain).
Security High (data never leaves server). Low (tamperable, visible to user).
Lifetime Until session expires (or browser close). Can set explicit expiry (persistent).
Data Capacity Large (server-dependent). Small (~4KB).
Dependency Often uses a cookie to store session ID. Independent; stored and sent by browser.
Sensitive Data Suitable (e.g., user ID, auth tokens). Avoid (store only identifiers).

[!TIP] Use sessions for sensitive/expanding data (auth, cart). Use cookies for non-sensitive preferences (theme, language). Always set HttpOnly and Secure flags for session cookies.


7.0 Advanced & Systemic Web Topics

7.1 Web Design Issues

7.1.1 Key Considerations
  1. Usability:

    • Intuitive navigation (consistent menus, breadcrumbs).

    • Clear calls-to-action (CTAs).

    • Fast load times (<3 seconds).

    • Readable typography (font size, contrast).

  2. Accessibility (WCAG):

    • Semantic HTML (<button>, <nav>).

    • alt text for images.

    • Keyboard navigable (focus states).

    • ARIA roles for dynamic content.

    • Color contrast ratio ≥ 4.5:1.

  3. Cross-Browser Compatibility:

    • Test on Chrome, Firefox, Safari, Edge.

    • Use CSS resets/normalize.

    • Vendor prefixes (-webkit-, -moz-).

    • Avoid browser-specific APIs without fallbacks.

  4. Performance:

    • Minimize HTTP requests (combine CSS/JS, image sprites).

    • Optimize images (WebP, lazy loading).

    • Minify/compress CSS/JS.

    • Leverage browser caching (Cache-Control headers).

    • Use CDNs for static assets.

    • Reduce server response time (optimize DB queries, caching).

[!TIP] Adopt mobile-first responsive design. Use tools like Google Lighthouse to audit performance, accessibility, SEO.

7.2 Database Bugs & Security

7.2.1 Common Vulnerabilities and Bugs
  1. SQL Injection:

    • Bug: Unsanitized user input concatenated into SQL queries.

    • Example: "SELECT * FROM users WHERE id = " . $_GET['id']

    • Fix: Use prepared statements with parameterized queries.

      
      $$\displaystyle stmt = $$conn->prepare("SELECT * FROM users WHERE id = ?");
      
      $$\displaystyle stmt->bind_param("i", $$_GET['id']);
      
      
  2. Cross-Site Scripting (XSS):

    • Bug: Injecting malicious scripts into pages viewed by others.

    • Fix: Escape output (htmlspecialchars() in PHP) and validate input.

  3. Cross-Site Request Forgery (CSRF):

    • Bug: Unauthorized actions via forged requests (e.g., state-changing GET).

    • Fix: Use anti-CSRF tokens in forms, validate on server.

  4. Authentication Flaws:

    • Weak password policies, no rate limiting, session fixation.

    • Fix: Strong hashing (password_hash()), regenerate session ID on login, implement logout.

  5. Insecure Direct Object References (IDOR):

    • Bug: Accessing objects via predictable IDs (e.g., /user?id=123).

    • Fix: Check user authorization for each resource access.

  6. Security Misconfiguration:

    • Default credentials, verbose error messages, unused services.

    • Fix: Harden server, disable directory listing, custom error pages.

  7. Sensitive Data Exposure:

    • Storing passwords in plaintext, unencrypted connections.

    • Fix: Encrypt data at rest (AES) and in transit (TLS/SSL).

[!TIP] Defense in Depth: Validate/sanitize input, use prepared statements, escape output, implement least-privilege DB accounts, keep software updated.

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in