2082

CSC329 · TU past paper

Web Technology 2082 question paper

The complete TU 2082 exam paper for Web Technology (CSC329), all 12 questions with solved model answers written to the mark scheme.

Tap a question to open its answer.

  1. 110 marksText Effects and shadowAnswer

    Define CSS. What is the use of CSS shadow effects? Write an HTML script with proper CSS as per the following description. Display a text content "CSIT Exam" in a div with id div1. The text should have a horizontal shadow of 3px and a vertical shadow of 2px. The shadow color should be green. Also set the horizontal and vertical shadow of the div to 10px respectively with the shadow color of div to blue.[10]

    CSS: Definition, Shadow Effects, and HTML Script


    1. Definition of CSS

    CSS (Cascading Style Sheets) is a style sheet language used to describe the presentation and formatting of HTML documents. It controls the layout, colors, fonts, spacing, and overall visual appearance of web pages.

    CSS separates content (HTML) from design (styling), making web pages more attractive, consistent, and easier to maintain across multiple pages.


    2. Use of CSS Shadow Effects

    CSS Shadow Effects are used to add visual depth and dimension to web page elements. They make text and boxes stand out from the background, improving the overall visual appeal of a webpage.

    CSS provides two main shadow properties:

    PropertyPurpose
    text-shadowAdds shadow to text content
    box-shadowAdds shadow to HTML elements (div, p, etc.)

    Syntax:

    text-shadow: h-shadow  v-shadow  color;
    box-shadow:  h-shadow  v-shadow  color;
    

    Where:

    • h-shadow -- Horizontal offset of the shadow (in px)
    • v-shadow -- Vertical offset of the shadow (in px)
    • color -- Color of the shadow

    3. HTML Script with CSS Shadow Effects

    Requirements:

    • A div with id="div1" containing the text "CSIT Exam"
    • Text shadow: horizontal = 3px, vertical = 2px, color = green
    • Box shadow: horizontal = 10px, vertical = 10px, color = blue
    <!DOCTYPE html>
    <html>
      <head>
        <title>CSS Shadow Effects</title>
        <style>
          #div1 {
            font-size: 30px;
            padding: 20px;
            margin: 50px;
            text-shadow: 3px 2px green;
            box-shadow: 10px 10px blue;
          }
        </style>
      </head>
      <body>
        <div id="div1">
          CSIT Exam
        </div>
      </body>
    </html>
    

    4. Explanation of Properties Used

    PropertyValueMeaning
    text-shadow3px 2px green3px horizontal, 2px vertical, green colored shadow on the text
    box-shadow10px 10px blue10px horizontal, 10px vertical, blue colored shadow on the div
    font-size30pxSets text size for visibility
    padding20pxAdds inner spacing inside the div
    margin50pxAdds outer spacing around the div

    Conclusion

    CSS shadow effects enhance the visual appearance of web pages by adding depth to both text and box elements. The text-shadow property applies shadow to text content, while the box-shadow property applies shadow to block-level elements such as div. Both properties accept horizontal offset, vertical offset, and color as values.

  2. 210 marksjQuery SelectorsAnswer

    What are jQuery selectors? Explain jQuery callback and chaining effects with appropriate jQuery scripts.[10]

    jQuery Selectors, Callback, and Chaining Effects


    1. jQuery Selectors

    jQuery selectors allow us to select and manipulate HTML elements. They are used to "find" (or select) HTML elements based on their name, id, class, attributes, and more.

    All selectors in jQuery start with the dollar sign and parentheses: $()

    Types of jQuery Selectors

    SelectorDescriptionExample
    Element SelectorSelects elements based on element name$("p") selects all <p> elements
    ID SelectorSelects a single element with a specific id$("#myId")
    Class SelectorSelects all elements with a specific class$(".myClass")
    Universal SelectorSelects all elements$("*")
    this SelectorRefers to the current HTML element$(this)

    Example of Element Selector

    $(document).ready(function() {
        $("button").click(function() {
            $("p").hide();
        });
    });
    

    When a user clicks the button, all <p> elements will be hidden.


    2. jQuery Callback

    A callback function is a function that is executed after the current effect is fully finished. This is important because jQuery effects take time (e.g., slow, fast, milliseconds), and without a callback, the next line of code may run before the effect completes.

    Syntax

    $(selector).hide(speed, callback);
    
    • speed - optional; can be "slow", "fast", or milliseconds
    • callback - optional; the function to execute after the effect completes

    Example of Callback

    $("button").click(function() {
        $("p").hide("slow", function() {
            alert("The paragraph is now hidden");
        });
    });
    

    Explanation:

    • When the button is clicked, the <p> element hides slowly.
    • Only after the hide effect is completely finished, the alert() callback function executes.
    • Without the callback, the alert might fire before the hiding animation completes.

    Another Callback Example with fadeIn

    $("button").click(function() {
        $("p").fadeIn(1000, function() {
            alert("Fade In complete!");
        });
    });
    

    3. jQuery Chaining

    Chaining allows us to run multiple jQuery methods/commands one after another on the same element(s) in a single statement. This makes code shorter and more efficient.

    To chain an action, we simply append the action to the previous action.

    Syntax

    $(selector).method1().method2().method3();
    

    Example of Chaining

    $("button").click(function() {
        $("#div").css("color", "red").slideUp(200).slideDown(200);
    });
    

    Explanation of the above example:

    1. css("color", "red") - changes the text color of #div to red
    2. .slideUp(200) - slides the element up in 200 milliseconds
    3. .slideDown(200) - slides the element back down in 200 milliseconds

    All three methods are applied to the same element #div one after another.

    Another Chaining Example

    $(document).ready(function() {
        $("button").click(function() {
            $("p")
                .css("color", "blue")
                .fadeOut(1000)
                .fadeIn(1000);
        });
    });
    

    Explanation:

    • The <p> element first turns blue.
    • Then it fades out over 1 second.
    • Then it fades back in over 1 second.

    Summary Table

    FeatureDescriptionKey Benefit
    SelectorsFind/select HTML elements by name, id, classEasy DOM access
    CallbackFunction executed after an effect finishesEnsures sequential execution
    ChainingMultiple methods applied to same element in one lineShorter, cleaner code

    Note: jQuery follows the syntax $(selector).action() where $ grants access to jQuery, selector finds HTML elements, and action() performs operations on them.

  3. 310 marksXSD Complex TypesAnswer

    What is the use of XML? Create an XML file having complex type elements containing other elements and text. At least one element should contain an attribute. Similarly, there should be elements containing string, integer and date type values. Now write the equivalent XSD for the XML.[10]

    XML: Uses, XML File with Complex Types, and Equivalent XSD


    Uses of XML

    XML (eXtensible Markup Language) is used for:

    • Data storage and transport between applications and systems
    • Platform-independent data exchange over the internet
    • Configuration files for software applications (e.g., web.xml, pom.xml)
    • Web services (SOAP, REST use XML for message formatting)
    • Document representation (e.g., Office documents, RSS feeds)
    • Database-like storage for small structured datasets
    • Separating data from presentation (used with XSLT for transformation)

    XML File with Complex Type Elements

    The following XML file represents a Library with Book records. It includes:

    • Complex type elements containing other elements and text
    • At least one element with an attribute
    • Elements with string, integer, and date type values
    <?xml version="1.0" encoding="UTF-8"?>
    <library>
    
        <book id="B001">
            <title>Introduction to Programming</title>
            <author>Dennis Ritchie</author>
            <publisher>
                <name>TechPress</name>
                <country>USA</country>
            </publisher>
            <price>1500</price>
            <publishedDate>2020-06-15</publishedDate>
            <available>true</available>
        </book>
    
        <book id="B002">
            <title>Data Structures and Algorithms</title>
            <author>Thomas Cormen</author>
            <publisher>
                <name>MIT Press</name>
                <country>USA</country>
            </publisher>
            <price>2200</price>
            <publishedDate>2018-03-10</publishedDate>
            <available>false</available>
        </book>
    
    </library>
    

    Explanation of the XML

    Element/AttributeTypeDescription
    <library>Root elementContains all book records
    <book id="B001">Complex type with attributeid is an attribute of book
    <title>, <author>, <name>, <country>StringText values
    <price>IntegerNumeric value
    <publishedDate>DateDate in YYYY-MM-DD format
    <publisher>Complex typeContains child elements <name> and <country>

    Equivalent XSD (XML Schema Definition)

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
        <!-- Root Element -->
        <xs:element name="library">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="book" type="bookType"
                                minOccurs="1" maxOccurs="unbounded"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    
        <!-- Complex Type: bookType -->
        <xs:complexType name="bookType">
            <xs:sequence>
                <xs:element name="title"         type="xs:string"/>
                <xs:element name="author"        type="xs:string"/>
                <xs:element name="publisher"     type="publisherType"/>
                <xs:element name="price"         type="xs:integer"/>
                <xs:element name="publishedDate" type="xs:date"/>
                <xs:element name="available"     type="xs:boolean"/>
            </xs:sequence>
            <!-- Attribute for book element -->
            <xs:attribute name="id" type="xs:string" use="required"/>
        </xs:complexType>
    
        <!-- Complex Type: publisherType (nested complex type) -->
        <xs:complexType name="publisherType">
            <xs:sequence>
                <xs:element name="name"    type="xs:string"/>
                <xs:element name="country" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    
    </xs:schema>
    

    Explanation of the XSD

    XSD ComponentPurpose
    xs:schemaRoot element of every XSD file
    xs:elementDeclares an XML element
    xs:complexTypeDefines elements that contain child elements or attributes
    xs:sequenceChild elements must appear in the defined order
    xs:attribute use="required"Declares id as a required attribute of <book>
    xs:stringSimple type for text values (title, author, name, country)
    xs:integerSimple type for whole number values (price)
    xs:dateSimple type for date values (publishedDate)
    xs:booleanSimple type for true/false values (available)
    minOccurs / maxOccursControls how many times an element can appear

    Note: XSD is like DTD but provides more control on XML structure. It supports predefined simple types such as xs:integer, xs:boolean, xs:string, and xs:date, and uses complex types as containers for other element definitions to build a hierarchy of elements.

  4. 45 marksWeb ClientsAnswer

    Define web clients and web servers with examples. [5]

    Web Clients and Web Servers

    Web Client

    A web client is a software application (typically a web browser) that runs on the user's machine and sends requests to a web server to retrieve and display web content. The client initiates communication by sending an HTTP request and then receives and renders the response (such as an HTML page, image, or other resource) for the user.

    Key characteristics of a web client:

    • Runs on the user's (client) side
    • Uses HTTP protocol to communicate with the server
    • Executes client-side scripts (e.g., JavaScript)
    • Renders HTML, CSS, and multimedia content

    Examples of web clients:

    • Google Chrome
    • Mozilla Firefox
    • Microsoft Edge
    • Opera Mini
    • Internet Explorer

    Web Server

    A web server is a computer program (or the machine running it) that stores, processes, and delivers web pages and resources to clients upon request. When a web server receives an HTTP request from a client, it fetches the requested resource and sends back an HTTP response.

    Key characteristics of a web server:

    • Runs on the server side
    • Listens for incoming HTTP requests
    • Processes requests and sends appropriate responses
    • Hosts websites, files, and web applications

    Examples of web servers:

    • Apache HTTP Server
    • Nginx
    • Microsoft IIS (Internet Information Services)
    • Border Manager (a multipurpose network security application also used as a proxy server)

    How They Work Together (Client-Server Model)

    According to the HTTP protocol, the interaction follows these steps:

    1. User enters a URL in the browser (web client)
    2. Browser uses DNS to locate the IP address of the server
    3. Browser opens a TCP connection to the web server
    4. Browser sends an HTTP request over the connection
    5. Server sends an HTTP response (with the requested web page or resource)
    6. Browser displays the content in the browser window
    [Web Client]  ----HTTP Request---->  [Web Server]
    (Browser)     <---HTTP Response----  (Apache/Nginx)
    

    Summary Table

    FeatureWeb ClientWeb Server
    LocationUser's machineRemote/host machine
    RoleSends requests, displays contentReceives requests, sends responses
    Protocol usedHTTPHTTP
    ExampleChrome, FirefoxApache, Nginx

    Note: This client-server model forms the foundation of the World Wide Web (WWW), which uses HTTP protocol and browsers to access information over the internet.

  5. 55 marksAudioAnswer

    Write an HTML script using audio tag. Set the autoplay, preload and loop properties to appropriate values. [5]

    The following HTML script demonstrates the use of the <audio tag with autoplay, preload, and loop properties set to appropriate values. --- Attribute Value Used Description ------------------------------------ controls (boolean) Adds aud...

  6. 65 marksHTML EventsAnswer

    Write an HTML script to demonstrate the onkeydown and onkeypress events. [5]

    HTML Script to Demonstrate onkeydown and onkeypress Events

    Brief Explanation

    Keyboard Events are:

    AttributeDescription
    onkeydownFires/runs when a user is pressing a key
    onkeypressFires when user presses a key
    onkeyupFires when user releases a key

    These are event handlers written inside HTML tags that execute JavaScript when something happens (such as pressing a key).


    HTML Script

    <!DOCTYPE html>
    <html>
    <head>
        <title>onkeydown and onkeypress Event Demo</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 40px;
            }
            input {
                padding: 8px;
                font-size: 16px;
                width: 300px;
            }
            #output {
                margin-top: 20px;
                padding: 10px;
                background-color: #f0f0f0;
                border: 1px solid #ccc;
                width: 320px;
            }
        </style>
    </head>
    <body>
    
        <h2>Keyboard Event Demo: onkeydown and onkeypress</h2>
    
        <p>Type something in the textbox below:</p>
    
        <input
            type="text"
            id="myInput"
            onkeydown="keyDownHandler(event)"
            onkeypress="keyPressHandler(event)"
            placeholder="Type here..."
        />
    
        <div id="output">
            <p id="keydown_msg">onkeydown: (waiting...)</p>
            <p id="keypress_msg">onkeypress: (waiting...)</p>
        </div>
    
        <script type="text/javascript">
    
            // Fires when a user is pressing a key (onkeydown)
            function keyDownHandler(event) {
                document.getElementById("keydown_msg").innerHTML =
                    "onkeydown: Key pressed down = " + event.key;
            }
    
            // Fires when user presses a key (onkeypress)
            function keyPressHandler(event) {
                document.getElementById("keypress_msg").innerHTML =
                    "onkeypress: Key pressed = " + event.key;
            }
    
        </script>
    
    </body>
    </html>
    

    Output / Explanation

    When the user types in the text box:

    • onkeydown fires first, as soon as the key is pushed down, and displays the key name in the output area.
    • onkeypress fires next, when the key press is registered, and also displays the key name.

    Example output when user presses the key A:

    onkeydown:  Key pressed down = A
    onkeypress: Key pressed = A
    

    Note: onkeypress does not fire for non-character keys (like Shift, Ctrl, Arrow keys), whereas onkeydown fires for all keys.

  7. 75 marksPopup BoxesAnswer

    Write an HTML script with proper JavaScript that will take an input from prompt box and display the input as output using the alert box. [5]

    • Prompt box is used to fetch/take value from the user. - Syntax: prompt("message", "default value"); - Alert box is used to display a message to the browser. - Syntax: alert("message"); The task is to combine both: take input using prom...
  8. 85 marksPositioningAnswer

    Create an HTML page containing three paragraphs p1, p2 and p3 with some contents. Write internal CSS to set the position of p1 to relative, p2 to float and p3 to absolute. [5]

    HTML Page with CSS Positioning (p1: relative, p2: float, p3: absolute)

    Concept (from notes)

    • position: relative - element is positioned relative to its normal position in the document flow.
    • float - used to float an element to the left or right, allowing other content to wrap around it.
    • position: absolute - element is positioned relative to the nearest positioned ancestor; removed from normal document flow and can overlap other elements.

    HTML Code

    <!DOCTYPE html>
    <html>
      <head>
        <title>CSS Positioning Example</title>
    
        <style>
          /* p1: position relative */
          #p1 {
            position: relative;
            top: 20px;
            left: 30px;
            background-color: lightblue;
            width: 300px;
            padding: 10px;
          }
    
          /* p2: float */
          #p2 {
            float: left;
            background-color: lightgreen;
            width: 250px;
            padding: 10px;
            margin: 10px;
          }
    
          /* p3: position absolute */
          #p3 {
            position: absolute;
            top: 200px;
            left: 400px;
            background-color: lightyellow;
            width: 300px;
            padding: 10px;
          }
        </style>
    
      </head>
    
      <body>
    
        <h2>CSS Positioning Demo</h2>
    
        <p id="p1">
          This is paragraph P1. Its position is set to <strong>relative</strong>.
          It is shifted 20px from top and 30px from left relative to its
          normal position in the document flow.
        </p>
    
        <p id="p2">
          This is paragraph P2. It uses <strong>float: left</strong>.
          This element floats to the left and other content
          wraps around it.
        </p>
    
        <p id="p3">
          This is paragraph P3. Its position is set to <strong>absolute</strong>.
          It is positioned relative to the nearest positioned ancestor
          or the document body. It is removed from the normal document flow.
        </p>
    
      </body>
    </html>
    

    Output Description

    ParagraphCSS PropertyEffect
    p1position: relativeShifted 20px down and 30px right from its normal position
    p2float: leftFloats to the left; other content wraps around it
    p3position: absolutePlaced at exact coordinates (top: 200px, left: 400px) from the document body; removed from normal flow

    Key Notes

    • Internal CSS is written inside the <style> tag placed within the <head> section.
    • The top, left, right, and bottom properties only work when the position property is explicitly set.
    • Absolute positioned elements are removed from normal flow and can overlap other elements.
  9. 95 marksBuilt-in ObjectsAnswer

    What is the use of alert box? Write a JavaScript program to show the use of RegExp object. [5]

    Alert Box and JavaScript RegExp Object

    Alert Box

    An alert box is a built-in JavaScript dialog box used to display a message or information to the user. It shows a popup window with a message and an OK button. The user must click OK to proceed.

    Uses of Alert Box:

    • To display important information or warnings to the user
    • To show validation error messages
    • To debug JavaScript code by displaying variable values
    • To notify the user about the result of an operation

    Syntax:

    alert("Your message here");
    

    RegExp Object in JavaScript

    A RegExp (Regular Expression) object is used to match character combinations in strings. It is used for pattern matching and text searching/replacing.

    Syntax:

    var pattern = new RegExp("pattern", "flags");
    // OR shorthand
    var pattern = /pattern/flags;
    

    Common Flags:

    FlagDescription
    iCase-insensitive matching
    gGlobal match (find all matches)
    mMultiline matching

    Common Methods:

    MethodDescription
    test()Returns true or false if pattern matches
    exec()Returns matched result or null

    JavaScript Program Using RegExp Object

    <!DOCTYPE html>
    <html>
    <head>
        <title>RegExp Object Example</title>
    </head>
    <body>
        <h2>RegExp Object Demo</h2>
    
        <form>
            <label>Enter Username:</label>
            <input type="text" id="username" />  
    
            <label>Enter Password:</label>
            <input type="text" id="password" />  
    
            <input type="button" value="Validate" onclick="validate()" />
        </form>
    
        <script type="text/javascript">
            function validate() {
                var uname = document.getElementById("username").value;
                var pwd   = document.getElementById("password").value;
    
                // Username: only letters and digits, minimum 5 characters
                var unamePattern = new RegExp("^[a-zA-Z0-9]{5,}$");
    
                // Password: must start with a digit and end with $
                var pwdPattern = /^\d.*\$$/;
    
                // Validate username
                if (!unamePattern.test(uname)) {
                    alert("Invalid username! Username must be at least 5 characters"
                          + " and contain only letters or digits.");
                    return;
                }
    
                // Validate password
                if (!pwdPattern.test(pwd)) {
                    alert("Invalid password! Password must start with a digit"
                          + " and end with '$'.");
                    return;
                }
    
                alert("Validation Successful! Welcome, " + uname);
            }
        </script>
    </body>
    </html>
    

    Explanation of Patterns Used

    PatternMeaning
    ^[a-zA-Z0-9]{5,}$Username starts (^) and ends ($) with alphanumeric characters, minimum 5
    ^\d.*\$$Password starts (^) with a digit (\d), has any characters (.*), and ends with $
    test()Returns true if the string matches the pattern, false otherwise

    Note: The alert() box is used here to display validation messages, demonstrating both the use of alert boxes and the RegExp object together.

  10. 105 marksCreating Class and ObjectsAnswer

    Write a PHP program to demonstrate the concept of inheritance. [5]

    PHP Program to Demonstrate Inheritance

    Concept of Inheritance in PHP

    Inheritance is an OOP concept where a child class (derived class) acquires the properties and methods of a parent class (base class) using the extends keyword. This promotes code reusability.


    PHP Program

    <?php
    
    // Parent Class (Base Class)
    class Animal {
        public $name;
        public $color;
    
        // Constructor of Parent Class
        public function __construct($name, $color) {
            $this->name  = $name;
            $this->color = $color;
        }
    
        // Method in Parent Class
        public function eat() {
            echo $this->name . " eats food. ";
        }
    
        public function display() {
            echo "Name  : " . $this->name  . " ";
            echo "Color : " . $this->color . " ";
        }
    }
    
    // Child Class (Derived Class) - inherits from Animal
    class Dog extends Animal {
        public $breed;
    
        // Constructor of Child Class
        public function __construct($name, $color, $breed) {
            // Call parent constructor using parent keyword
            parent::__construct($name, $color);
            $this->breed = $breed;
        }
    
        // Method specific to Child Class
        public function bark() {
            echo $this->name . " says: Woof! Woof! ";
        }
    
        // Overriding parent method (Method Overriding)
        public function display() {
            parent::display();
            echo "Breed : " . $this->breed . " ";
        }
    }
    
    // Creating object of Parent Class
    echo "<b>--- Animal Object ---</b> ";
    $animal = new Animal("Cat", "White");
    $animal->display();
    $animal->eat();
    
    echo " ";
    
    // Creating object of Child Class
    echo "<b>--- Dog Object (Child Class) ---</b> ";
    $dog = new Dog("Tommy", "Brown", "Labrador");
    $dog->display();   // Calls overridden display()
    $dog->eat();       // Inherited from Animal
    $dog->bark();      // Own method of Dog
    
    ?>
    

    Output

    --- Animal Object ---
    Name  : Cat
    Color : White
    Cat eats food.
    
    --- Dog Object (Child Class) ---
    Name  : Tommy
    Color : Brown
    Breed : Labrador
    Tommy eats food.
    Tommy says: Woof! Woof!
    

    Key Points Demonstrated

    ConceptDescription
    extendsUsed to inherit parent class into child class
    parent::__construct()Calls the constructor of the parent class
    Inherited methodeat() is defined in Animal but used by Dog
    Method Overridingdisplay() is redefined in Dog class
    Child-specific methodbark() belongs only to Dog class
  11. 115 marksInserting Multiple DataAnswer

    Write a PHP program to show insertion of multiple data into a database table. [5]

    The program follows the standard MySQLi procedural approach as described in the curriculum notes: 1. Establish a database connection using mysqliconnect() 2. Select the target database 3. Insert multiple rows using multiple INSERT SQL qu...

  12. 125 marksForm ValidationAnswer

    Create a PHP form with form elements. Write a program to perform form validation. Use your own assumptions for the validation. [5]

    PHP Form with Validation

    Assumptions for Validation:

    • Username: required, minimum 5 characters
    • Password: required, must start with a digit and end with $
    • Gender (radio button): must be selected
    • Hobbies (checkbox): at least one must be checked

    Complete PHP Program

    <?php
    // Initialize variables
    $username = $password = $gender = "";
    $hobbies = [];
    $errors = [];
    $success = "";
    
    // Process form on submission
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
        // Username Validation
        if (empty($_POST["username"])) {
            $errors[] = "Username is required.";
        } else {
            $username = trim($_POST["username"]);
            if (strlen($username) < 5) {
                $errors[] = "Username must be at least 5 characters long.";
            }
        }
    
        // Password Validation
        if (empty($_POST["password"])) {
            $errors[] = "Password is required.";
        } else {
            $password = trim($_POST["password"]);
            // Must start with a digit and end with $
            if (!preg_match('/^\d/', $password) || !preg_match('/\$$/', $password)) {
                $errors[] = "Password must start with a digit and end with '$'.";
            }
        }
    
        // Gender Validation (Radio Button)
        if (empty($_POST["gender"])) {
            $errors[] = "Please select your gender.";
        } else {
            $gender = $_POST["gender"];
        }
    
        // Hobbies Validation (Checkbox)
        if (empty($_POST["hobbies"])) {
            $errors[] = "Please select at least one hobby.";
        } else {
            $hobbies = $_POST["hobbies"];
        }
    
        // If no errors, show success
        if (empty($errors)) {
            $success = "Form submitted successfully! Welcome, " . htmlspecialchars($username) . ".";
        }
    }
    ?>
    
    <!DOCTYPE html>
    <html>
    <head>
        <title>PHP Form Validation</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 30px; }
            .error { color: red; }
            .success { color: green; font-weight: bold; }
            label { display: inline-block; width: 120px; }
            input[type="text"], input[type="password"] {
                padding: 5px;
                width: 200px;
            }
            .form-group { margin: 10px 0; }
        </style>
    </head>
    <body>
    
    <h2>Registration Form</h2>
    
    <!-- Display Errors -->
    <?php if (!empty($errors)): ?>
        <ul class="error">
            <?php foreach ($errors as $error): ?>
                <li><?php echo $error; ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
    
    <!-- Display Success -->
    <?php if (!empty($success)): ?>
        <p class="success"><?php echo $success; ?></p>
    <?php endif; ?>
    
    <!-- HTML Form -->
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    
        <!-- Username -->
        <div class="form-group">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username"
                   value="<?php echo htmlspecialchars($username); ?>">
        </div>
    
        <!-- Password -->
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
        </div>
    
        <!-- Gender (Radio Buttons) -->
        <div class="form-group">
            <label>Gender:</label>
            <input type="radio" name="gender" value="Male"
                <?php echo ($gender == "Male") ? "checked" : ""; ?>> Male
            <input type="radio" name="gender" value="Female"
                <?php echo ($gender == "Female") ? "checked" : ""; ?>> Female
            <input type="radio" name="gender" value="Other"
                <?php echo ($gender == "Other") ? "checked" : ""; ?>> Other
        </div>
    
        <!-- Hobbies (Checkboxes) -->
        <div class="form-group">
            <label>Hobbies:</label>
            <input type="checkbox" name="hobbies[]" value="Reading"
                <?php echo (in_array("Reading", $hobbies)) ? "checked" : ""; ?>> Reading
            <input type="checkbox" name="hobbies[]" value="Gaming"
                <?php echo (in_array("Gaming", $hobbies)) ? "checked" : ""; ?>> Gaming
            <input type="checkbox" name="hobbies[]" value="Coding"
                <?php echo (in_array("Coding", $hobbies)) ? "checked" : ""; ?>> Coding
            <input type="checkbox" name="hobbies[]" value="Travelling"
                <?php echo (in_array("Travelling", $hobbies)) ? "checked" : ""; ?>> Travelling
        </div>
    
        <!-- Submit Button -->
        <div class="form-group">
            <input type="submit" value="Register">
        </div>
    
    </form>
    
    </body>
    </html>
    

    Key Points Explained

    ElementValidation Rule
    usernameRequired, length >= 5
    passwordRequired, starts with digit, ends with $
    genderRadio button must be selected
    hobbies[]At least one checkbox must be checked
    • $_SERVER["REQUEST_METHOD"] == "POST" checks if the form is submitted.
    • preg_match() is used for pattern-based password validation.
    • htmlspecialchars() prevents XSS attacks on output.
    • empty($errors)