Board paper

Web Programming II 2021 Board Question Paper

ITM 251 · Web Programming II

Programme
BITM / BIM
Academic year
Semester 4
Exam year
2021 AD
Sitting
regular
Full marks
40
Duration
120 minutes

Tribhuvan University

Faculty of Management

Office of the Dean

2021 AD / Regular Examination

Course: ITM 251 · Web Programming II

Level: Bachelor of Information Technology Management (BITM / BIM) (BITM / BIM) · Semester 4

Full Marks: 40

Time: 2 hrs.

Time: 2 hrs | Full Marks: 40 | Pass Marks: 20

Subjective Questions

  1. How do you create 2-D array in PHP?

    [2]
    View model solution

    Creating a 2D Array in PHP

    In PHP, a two-dimensional (2D) array is an array of arrays. It can be initialized using the short array syntax [] or the legacy array() constructor:

    <?php
    // Creating a 2D array of students with name, roll, and semester
    $students = [
        ["name" => "Aarav Sharma", "roll" => 101, "semester" => "4th"],
        ["name" => "Pooja Thapa",  "roll" => 102, "semester" => "4th"],
        ["name" => "Bikash KC",    "roll" => 103, "semester" => "4th"]
    ];
    
    // Accessing an element:
    echo $students[0]["name"]; // Outputs: Aarav Sharma
    ?>
    
  2. Differentiate between client side and server side scripting language.

    [2]
    View model solution

    Client-Side vs. Server-Side Scripting

    Feature Client-Side Scripting (e.g., JavaScript) Server-Side Scripting (e.g., PHP)
    Execution Location Executed inside the client’s web browser. Executed entirely on the web server.
    Source Code Visibility Viewable by users via ‘View Page Source’. Source code remains private; only output (HTML/JSON) is sent.
    Primary Role UI interactivity, animation, instant input validation. Business logic, database operations, user authentication.
    Database Access Cannot directly connect to back-end databases. Directly queries and updates databases (MySQL, PostgreSQL).
  3. How do you inspect file permission inPHP?

    [2]
    View model solution

    Inspecting File Permissions in PHP

    In PHP, file permissions are inspected using the built-in fileperms() function, which returns the permissions as a numeric bitmask, formatted typically in octal:

    <?php
    $filename = "records.txt";
    if (file_exists($filename)) {
        // Retrieve permissions and convert last 4 octal digits
        $perms = decoct(fileperms($filename) & 0777);
        echo "Permissions for {$filename}: " . $perms; // e.g., 0644 or 0755
    }
    ?>
    

    Additionally, is_readable($file) and is_writable($file) test specific read and write capabilities directly.

  4. Write a statement to create a 2D array in PHP ?

    [2]
    View model solution

    Statement to Create a 2D Array in PHP

    A statement defining an indexed 2D matrix in PHP:

    <?php
    // Statement creating a 3x3 numeric matrix
    $matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];
    ?>
    

    This stores rows at indices 0, 1, 2 and columns at nested indices 0, 1, 2.

  5. Write the syntax for do .. while loop in PHP ?

    [2]
    View model solution

    Syntax for do...while Loop in PHP

    A do...while loop is an exit-controlled loop that executes its block of code at least once before evaluating the condition:

    <?php
    do {
        // Code statement(s) to execute
    } while (condition);
    ?>
    

    Example:

    <?php
    $count = 1;
    do {
        echo "Iteration: $count <br>";
        $count++;
    } while ($count <= 5);
    ?>
    
  6. What do you mean by POST method?

    [2]
    View model solution

    What is the POST Method?

    The HTTP POST Method is an HTTP request verb used to submit data to a server to create or process a resource (e.g., submitting form data, uploading files, sending passwords).

    Key Characteristics:

    1. Body Encapsulation: Form values are transmitted inside the HTTP request payload body rather than appended to the browser URL string.
    2. Security & Confidentiality: Sensitive parameters (passwords, payment details) are not visible in the browser address bar or stored in browser histories.
    3. No Length Limitations: Unlike GET, POST requests can transmit large payloads and binary file attachments.
    4. PHP Access: Form fields are accessed server-side via the superglobal associative array $_POST['field_name'].
  7. How can you prevent SQL injection inPHP?

    [2]
    View model solution

    Preventing SQL Injection in PHP

    SQL Injection (SQLi) occurs when malicious SQL statements are inserted into entry fields and executed by the backend database engine.

    Primary Defense: Prepared Statements with Parameterized Queries

    Instead of concatenating raw strings into SQL commands, use PDO (PHP Data Objects) or MySQLi prepared statements:

    <?php
    // Secure PDO Prepared Statement
    $stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = :email AND status = :status");
    $stmt->execute([
        ':email' => $_POST['email'],
        ':status' => 'active'
    ]);
    $user = $stmt->fetch();
    ?>
    

    In prepared statements, the database engine treats input parameters strictly as data literals—never as executable SQL tokens—completely neutralizing injection attempts.

  8. Write a PHP program to display the current date in PHP ?

    [2]
    View model solution

    PHP Program to Display the Current Date

    <?php
    // Set timezone (e.g., Asia/Kathmandu for Nepal)
    date_default_timezone_set('Asia/Kathmandu');
    
    // Display formatted date and time
    echo "Today is: " . date("Y-m-d H:i:s") . "<br>";
    echo "Formatted: " . date("l, F j, Y"); // e.g., Friday, September 11, 2026
    ?>
    
  9. What is the use of mktime()?

    [2]
    View model solution

    Use of mktime() in PHP

    The mktime() function in PHP generates a Unix timestamp (the number of seconds elapsed since January 1, 1970 00:00:00 GMT) corresponding to the given date and time arguments.

    Syntax:

    mktime(hour, minute, second, month, day, year);
    

    Example Usage:

    <?php
    // Timestamp for October 24, 2026 at 15:30:00
    $timestamp = mktime(15, 30, 0, 10, 24, 2026);
    echo "Generated Timestamp: " . $timestamp;
    echo "Readable Date: " . date("Y-m-d H:i:s", $timestamp);
    ?>
    
  10. How can you generate a unique id in PHP?

    [2]
    View model solution

    Generating a Unique ID in PHP

    PHP provides built-in functions to generate unique identifiers:

    1. uniqid(): Generates a unique string based on the current microsecond system clock:
      <?php
      // Prefix 'usr_' with more_entropy = true for high randomness
      $uniqueId = uniqid('usr_', true);
      echo $uniqueId; // e.g., usr_66e07a9e14c2b9.12345678
      ?>
      
    2. Cryptographically Secure UUID v4 (Modern PHP):
      <?php
      $uuid = bin2hex(random_bytes(16));
      ?>
      
  11. Write a PHP function that accepts an array of integers and display in ascending order.

    [5]
    View model solution

    PHP Function to Sort and Display an Array in Ascending Order

    <?php
    function sortAndDisplayArray(array $numbers): void {
        echo "Original Array: " . implode(", ", $numbers) . "<br>";
    
        // Sort the array in ascending order (modifies array in place)
        sort($numbers);
    
        echo "Sorted Array (Ascending): " . implode(", ", $numbers) . "<br>";
    
        // Display in an HTML ordered list
        echo "<ol>";
        foreach ($numbers as $num) {
            echo "<li>" . htmlspecialchars((string)$num) . "</li>";
        }
        echo "</ol>";
    }
    
    // Driver Test Call
    $sampleData = [45, 12, 89, 3, 27, 64, 18];
    sortAndDisplayArray($sampleData);
    ?>
    
  12. Write a PHP program to demonstrate that contain a textbox for name , a textbox for age and a textarea for comments. Validate the data before submitting the data to the server. Assume all the required validations and age must be between 1 to 100.

    [5]
    View model solution

    Web Form with Client-Side JavaScript Validation

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>User Feedback Form</title>
      <script>
        function validateForm(event) {
          const name = document.getElementById("name").value.trim();
          const age = parseInt(document.getElementById("age").value, 10);
          const comments = document.getElementById("comments").value.trim();
          const errors = [];
    
          if (name === "") {
            errors.push("Name field cannot be empty.");
          }
          if (isNaN(age) || age < 1 || age > 100) {
            errors.push("Age must be an integer between 1 and 100.");
          }
          if (comments.length < 5) {
            errors.push("Comments must be at least 5 characters long.");
          }
    
          if (errors.length > 0) {
            event.preventDefault(); // Stop form submission
            alert("Validation Errors:\n" + errors.join("\n"));
            return false;
          }
          return true;
        }
      </script>
    </head>
    <body>
      <h2>User Feedback Form</h2>
      <form action="process.php" method="POST" onsubmit="return validateForm(event)">
        <p>
          <label for="name">Name:</label><br>
          <input type="text" id="name" name="name" required>
        </p>
        <p>
          <label for="age">Age (1-100):</label><br>
          <input type="number" id="age" name="age" min="1" max="100" required>
        </p>
        <p>
          <label for="comments">Comments:</label><br>
          <textarea id="comments" name="comments" rows="4" cols="30" required></textarea>
        </p>
        <button type="submit">Submit Feedback</button>
      </form>
    </body>
    </html>
    
  13. Write a PHP program to insert subject code, subject description, credit into database . Make all the required assumptions about the database.

    [5]
    View model solution

    PHP Program to Insert Subject Record into MySQL Database

    <?php
    // Database credentials and DSN configuration
    $host = "localhost";
    $db   = "tu_curriculum";
    $user = "db_user";
    $pass = "secret123";
    $charset = "utf8mb4";
    
    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    
    try {
        $pdo = new PDO($dsn, $user, $pass, $options);
    
        // Subject data to insert
        $subjectCode = "ITM 251";
        $subjectDescription = "Web Programming II (Server Side Scripting and Database)";
        $creditHours = 3;
    
        // Prepared statement to prevent SQL Injection
        $sql = "INSERT INTO subjects (subject_code, subject_description, credit)
                VALUES (:code, :description, :credit)";
    
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':code'        => $subjectCode,
            ':description' => $subjectDescription,
            ':credit'      => $creditHours
        ]);
    
        echo "<h3>Success: Subject successfully inserted! (ID: " . $pdo->lastInsertId() . ")</h3>";
    
    } catch (PDOException $e) {
        echo "<h3>Database Error: " . htmlspecialchars($e->getMessage()) . "</h3>";
    }
    ?>
    
  14. Write a PHP program to create a webform with two textboxes (name and age), a radio button for gender and a submit button. When a submit button is clicked, save the data to the file named “Person.txt.”

    [5]
    View model solution

    PHP Form to Save Submitted Data into a File (Person.txt)

    <?php
    $message = "";
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $name = trim($_POST["name"] ?? "");
        $age = trim($_POST["age"] ?? "");
        $gender = trim($_POST["gender"] ?? "");
    
        if (!empty($name) \&\& !empty($age) && !empty($gender)) {
            $record = "Name: $name | Age: $age | Gender: $gender | Date: " . date("Y-m-d H:i:s") . PHP_EOL;
    
            // Append to Person.txt with file lock
            file_put_contents("Person.txt", $record, FILE_APPEND | LOCK_EX);
            $message = "Record successfully saved to Person.txt!";
        } else {
            $message = "All fields are required!";
        }
    }
    ?>
    <!DOCTYPE html>
    <html>
    <body>
      <h2>Person Information Form</h2>
      <?php if ($message): ?><p><strong><?= htmlspecialchars($message) ?></strong></p><?php endif; ?>
      <form method="POST">
        <p>Name: <input type="text" name="name" required></p>
        <p>Age: <input type="number" name="age" min="1" max="120" required></p>
        <p>Gender:
          <input type="radio" name="gender" value="Male" required> Male
          <input type="radio" name="gender" value="Female"> Female
          <input type="radio" name="gender" value="Other"> Other
        </p>
        <button type="submit">Save to Person.txt</button>
      </form>
    </body>
    </html>
    
  15. Write a program to demonstrate session variable in PHP.

    [5]
    View model solution

    Demonstrating Session Variables in PHP

    PHP sessions store user data on the server across multiple page requests using a unique session ID passed via cookie.

    <?php
    // Step 1: Start or resume existing session (MUST be called before any HTML output)
    session_start();
    
    // Step 2: Storing data in session variables
    $_SESSION["user_id"] = 1042;
    $_SESSION["username"] = "rajesh_sharma";
    $_SESSION["role"] = "Admin";
    $_SESSION["login_time"] = time();
    
    echo "<h2>Session Initialized</h2>";
    echo "Username stored: " . htmlspecialchars($_SESSION["username"]) . "<br>";
    
    // Step 3: Accessing and updating session variables
    if (isset($_SESSION["views"])) {
        $_SESSION["views"]++;
    } else {
        $_SESSION["views"] = 1;
    }
    echo "Number of page visits in this session: " . $_SESSION["views"] . "<br>";
    
    // Step 4: Destroying session when user logs out
    // session_unset();    // Free all session variables
    // session_destroy();  // Destroy the session storage on server
    ?>
    
  16. Explain default values in form with example.

    [5]
    View model solution

    Default Values in HTML Forms with PHP

    Default form values pre-populate input controls when the form renders initially or preserve previously entered values when re-displaying the form following server-side validation errors (sticky forms).

    Example: Sticky Form with Default Values

    <?php
    // Default values or submitted values
    $country = $_POST['country'] ?? 'Nepal';
    $newsletter = isset($_POST['newsletter']) ? true : false;
    $username = $_POST['username'] ?? 'student_tu';
    ?>
    
    <form method="POST">
      <!-- Textbox with default value -->
      <label>Username:</label>
      <input type="text" name="username" value="<?= htmlspecialchars($username) ?>"><br><br>
    
      <!-- Dropdown with selected default -->
      <label>Country:</label>
      <select name="country">
        <option value="Nepal" <?= ($country === 'Nepal') ? 'selected' : '' ?>>Nepal</option>
        <option value="India" <?= ($country === 'India') ? 'selected' : '' ?>>India</option>
        <option value="Japan" <?= ($country === 'Japan') ? 'selected' : '' ?>>Japan</option>
      </select><br><br>
    
      <!-- Checkbox with checked default -->
      <label>
        <input type="checkbox" name="newsletter" value="1" <?= $newsletter ? 'checked' : '' ?>>
        Subscribe to newsletter
      </label><br><br>
    
      <button type="submit">Submit</button>
    </form>
    
  17. Write short notes on (any two) a. Variable scope b. Changing the format of Retried rows c. Cross site scripting attack and its prevention

    [10]
    View model solution

    Short Notes

    a. Variable Scope in PHP

    Variable scope determines the context within which a variable is accessible:

    1. Local Scope: Variables declared inside a function exist solely within that function and are destroyed upon return.
    2. Global Scope: Variables defined outside functions cannot be accessed directly inside functions unless imported using the global keyword (e.g., global $x;) or through the $GLOBALS['x'] superglobal array.
    3. Static Scope: A local variable declared with the static keyword (static $counter = 0;) retains its value across repeated function calls.
    4. Superglobals: Built-in associative arrays available everywhere across all scopes ($_GET, $_POST, $_SESSION, $_SERVER, $_COOKIE).

    c. Cross-Site Scripting (XSS) Attack and Its Prevention

    Cross-Site Scripting (XSS) occurs when an application includes untrusted user input in a web page without proper encoding or sanitization, allowing malicious attackers to execute client-side JavaScript in the victims’ browsers (stealing session cookies, tokens, or defacing UI).

    Types of XSS:

    • Stored (Persistent) XSS: Malicious payload is saved in the database (e.g., comments) and served to all viewers.
    • Reflected (Non-Persistent) XSS: Payload is reflected immediately off the web server via URL query parameters or form errors.

    Prevention Strategies in PHP:

    1. Context-Aware Output Encoding: Always escape user data before echoing it into HTML using htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8').
    2. HTTP-Only Cookies: Set session cookies with httponly: true so client-side JavaScript cannot read document.cookie.
    3. Content Security Policy (CSP): Enforce HTTP headers restricting script execution sources.