ITM 251

Web Programming II

TU BITM / BIM · Semester 4 · BIM curriculum effective from 2021

Requirement
required
Credits
3
Past papers
2 papers

Past exam papers

Complete papers are arranged by exam year (AD).

Web Programming II 2023 Board Question Paper

Report problem

Tribhuvan University

Faculty of Management

Office of the Dean

2023 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. What is difference between cookie and session?

    [2]
    View model solution

    Difference Between Cookie and Session

    Feature Cookie Session
    Storage Location Stored on the client’s machine (browser cache). Stored securely on the web server.
    Data Capacity Limited to approximately 4 KB per cookie. Virtually unlimited (bounded only by server RAM/disk).
    Security Vulnerable to user tampering, theft, and XSS. Highly secure; client only holds an opaque Session ID.
    Lifetime Persists until expired or cleared manually. Typically expires when browser closes or inactivity timeout.
  2. How can we place a double quote character in a double-quoted string?

    [2]
    View model solution

    Placing a Double Quote in a Double-Quoted String in PHP

    To include a double quote (") inside a double-quoted string literal in PHP, use the backslash escape character \":

    <?php
    $str = "He said, \"Welcome to Tribhuvan University!\"";
    echo $str; // Outputs: He said, "Welcome to Tribhuvan University!"
    ?>
    
  3. How does file opening mode “w” differ with “w+”?

    [2]
    View model solution

    Difference Between File Opening Modes “w” and “w+” in PHP

    • "w" (Write-Only Mode): Opens the file for writing only. Truncates the file length to zero (erases existing contents) or creates a new file if it does not exist. File pointer is placed at the beginning. Reading is not allowed.
    • "w+" (Read and Write Mode): Opens the file for both reading and writing. Like "w", it truncates the file to zero bytes or creates a new file if it does not exist, but allows the program to read back what was written.
  4. Write a syntax to declare a function.

    [2]
    View model solution

    Syntax to Declare a Function in PHP

    <?php
    function functionName(type $parameter1, type $parameter2 = defaultValue): returnType {
        // Function body
        return $value;
    }
    ?>
    

    Example:

    <?php
    function calculateTotal(float $price, int $quantity): float {
        return $price * $quantity;
    }
    ?>
    
  5. How do we find the length of an array?

    [2]
    View model solution

    Finding the Length of an Array in PHP

    In PHP, the length (number of elements) of an array is determined using the built-in count() function or its alias sizeof():

    <?php
    $fruits = ["Apple", "Banana", "Orange", "Mango"];
    $length = count($fruits);
    echo "Total items: " . $length; // Outputs: Total items: 4
    ?>
    
  6. How do you set default values for function parameter?

    [2]
    View model solution

    Setting Default Values for Function Parameters

    Default values are assigned directly to parameter variables in the function definition header using the assignment operator =:

    <?php
    function greetUser(string $name, string $greeting = "Namaste"): string {
        return "$greeting, $name!";
    }
    
    echo greetUser("Suman");          // Outputs: Namaste, Suman!
    echo greetUser("John", "Hello");   // Outputs: Hello, John!
    ?>
    

    Default parameters should be placed after all non-default parameters.

  7. What is the task of gettimeofday() function?

    [2]
    View model solution

    Task of gettimeofday() Function in PHP

    The gettimeofday() function retrieves the current system time with microsecond precision.

    • When called with no arguments (gettimeofday()), it returns an associative array with keys:
      • sec: Seconds since the Unix Epoch.
      • usec: Microseconds.
      • minuteswest: Minutes west of Greenwich.
      • dsttime: Type of DST correction.
    • When called with gettimeofday(true), it returns the current time as a floating-point number representing seconds since Unix Epoch.
  8. What is SQL injection attack?

    [2]
    View model solution

    What is a SQL Injection Attack?

    A SQL Injection (SQLi) attack is a cybersecurity vulnerability where an attacker manipulates user inputs (via form fields, headers, or URL query parameters) to inject malicious SQL commands into an application’s database queries. This enables unauthorized actors to bypass authentication, dump sensitive database tables, modify data, or drop entire databases.

  9. Why do we need default values feature in a form?

    [2]
    View model solution

    Why We Need the Default Values Feature in a Form

    1. User Convenience & Speed: Pre-fills common answers (such as default country, current date, or standard quantity), minimizing repetitive typing.
    2. Sticky Form State: Preserves the user’s previously typed input when re-rendering the form after validation errors, preventing frustration.
    3. Data Quality & Guidance: Demonstrates expected input formats (e.g., standard placeholders and default radio button selections).
  10. How do you declare multi dimensional array?

    [2]
    View model solution

    Declaring a Multi-Dimensional Array in PHP

    <?php
    $departments = [
        "IT" => [
            ["id" => 1, "name" => "Aayush", "role" => "Developer"],
            ["id" => 2, "name" => "Sneha",  "role" => "Architect"]
        ],
        "HR" => [
            ["id" => 3, "name" => "Rohan",  "role" => "Manager"]
        ]
    ];
    ?>
    
  11. How do you define the scope of variable? Justify with an example.

    [5]
    View model solution

    Variable Scope in PHP with Examples

    The scope of a variable defines the region of code in which it can be referenced. PHP provides three primary variable scopes:

    <?php
    $globalVar = 100; // Global Scope
    
    function testScope() {
        // 1. Local Scope
        $localVar = 50;
    
        // Accessing global variable requires 'global' keyword
        global $globalVar;
        echo "Global inside function: $globalVar <br>";
        echo "Local inside function: $localVar <br>";
    
        // 2. Static Scope: preserves value between calls
        static $counter = 0;
        $counter++;
        echo "Static Counter: $counter <br>";
    }
    
    testScope(); // Counter: 1
    testScope(); // Counter: 2
    // echo $localVar; // Fatal Error: Undefined variable in global scope
    ?>
    
  12. How do you create, store and retrieve session? Explain.

    [5]
    View model solution

    Creating, Storing, and Retrieving Sessions in PHP

    Sessions allow state preservation across multiple HTTP requests:

    1. Starting a Session:

    session_start() must be invoked at the top of every PHP script before sending any HTML or output headers:

    <?php
    session_start();
    

    2. Storing Data in Session:

    Store values using the superglobal $_SESSION associative array:

    $_SESSION["authenticated"] = true;
    $_SESSION["user_email"] = "student@tu.edu.np";
    $_SESSION["cart_items"] = [101, 204, 305];
    

    3. Retrieving Data from Session:

    Check existence with isset() and read values:

    if (isset($_SESSION["authenticated"]) && $_SESSION["authenticated"] === true) {
        echo "Welcome back, " . htmlspecialchars($_SESSION["user_email"]);
    }
    

    4. Terminating a Session:

    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"]);
    }
    session_destroy();
    
  13. Explain about different parameters passed to the setcookie() function.

    [5]
    View model solution

    Parameters of the setcookie() Function in PHP

    The setcookie() function sends a Set-Cookie HTTP header to the client browser.

    Signature:

    setcookie(name, value, expires_or_options, path, domain, secure, httponly);
    

    Explanation of Parameters:

    1. name (string, required): The identifier name of the cookie (e.g., 'auth_token').
    2. value (string, optional): The text content stored in the cookie.
    3. expires_or_options (int, optional): The Unix timestamp when the cookie expires (e.g., time() + 86400 for 1 day). 0 means session cookie.
    4. path (string, optional): The server directory path on which the cookie is valid (e.g., '/' for entire domain).
    5. domain (string, optional): The domain/subdomain that can access the cookie (e.g., 'tu.edu.np').
    6. secure (bool, optional): If true, the cookie is transmitted only over HTTPS connections.
    7. httponly (bool, optional): If true, prevents client-side JavaScript access (document.cookie), mitigating XSS cookie theft.
  14. The keys of an associative array contains the names of the books where as the value contains the name of author. Write a PHP program to display a table with two columns where the first column contains the name of the book and the second column contains the names of corresponding author.

    [5]
    View model solution

    PHP Program: Display Associative Array of Books and Authors in HTML Table

    <?php
    // Associative array: Book Title => Author Name
    $books = [
        "Computer Organization and Architecture" => "William Stallings",
        "Database System Concepts"               => "Silberschatz, Korth & Sudarshan",
        "Web Technologies: HTML, CSS & PHP"      => "Robin Nixon",
        "Data Structures Using C and C++"        => "Tanenbaum & Langsam",
        "Microprocessor Architecture (8085)"     => "Ramesh Gaonkar"
    ];
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Library Catalog</title>
      <style>
        table { border-collapse: collapse; width: 60%; margin: 20px auto; font-family: sans-serif; }
        th, td { border: 1px solid #ddd; padding: 10px 14px; text-align: left; }
        th { background-color: #2b2b2b; color: white; }
        tr:nth-child(even) { background-color: #f9f9f9; }
      </style>
    </head>
    <body>
      <h2 style="text-align: center;">Recommended Academic Textbooks</h2>
      <table>
        <thead>
          <tr>
            <th>Book Title</th>
            <th>Author Name</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($books as $title => $author): ?>
            <tr>
              <td><?= htmlspecialchars($title) ?></td>
              <td><?= htmlspecialchars($author) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </body>
    </html>
    
  15. Write a program to get Id, Name and address from a database of the employees of Tribhuvan University and store those information in a CSV file. Assumptions to be made for the database are : database name is “TU”, table name is “employees”, database username is “Tribhuvan” and password is “BIM76” and the database server URL is “fomeed.edu.np”.

    [5]
    View model solution

    PHP Program to Export Employee Data from MySQL to CSV

    <?php
    // Database configuration as specified
    $host     = "fomeed.edu.np";
    $dbname   = "TU";
    $username = "Tribhuvan";
    $password = "BIM76";
    $csvFile  = "employees.csv";
    
    $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
    
    try {
        // 1. Establish PDO Connection
        $pdo = new PDO($dsn, $username, $password, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]);
    
        // 2. Query Id, Name, and Address from employees table
        $stmt = $pdo->query("SELECT id, name, address FROM employees");
    
        // 3. Open CSV file for writing
        $fp = fopen($csvFile, "w");
        if ($fp === false) {
            die("Error opening file $csvFile for writing.");
        }
    
        // 4. Write CSV Header row
        fputcsv($fp, ["Employee ID", "Full Name", "Address"]);
    
        // 5. Fetch and write each row
        $rowCount = 0;
        while ($row = $stmt->fetch()) {
            fputcsv($fp, [$row['id'], $row['name'], $row['address']]);
            $rowCount++;
        }
    
        // 6. Close file resource
        fclose($fp);
        echo "Successfully exported $rowCount employee records to $csvFile.";
    
    } catch (PDOException $e) {
        echo "Database connection failed: " . htmlspecialchars($e->getMessage());
    }
    ?>
    
  16. Write a PHP program to find the difference between any two dates.

    [5]
    View model solution

    PHP Program to Find the Difference Between Any Two Dates

    <?php
    function getDateDifference(string $date1Str, string $date2Str): string {
        // Create DateTime objects
        $date1 = new DateTime($date1Str);
        $date2 = new DateTime($date2Str);
    
        // Calculate difference (returns DateInterval object)
        $interval = $date1->diff($date2);
    
        return sprintf(
            "%d years, %d months, %d days (Total days: %d days)",
            $interval->y,
            $interval->m,
            $interval->d,
            $interval->days
        );
    }
    
    // Example usage
    $start = "2024-01-15";
    $end   = "2026-09-11";
    echo "Date 1: $start <br>";
    echo "Date 2: $end <br>";
    echo "Difference: " . getDateDifference($start, $end);
    ?>
    
  17. Assume a file name “sport.txt” containing the news about cricket. Print the portion of file between the first two consecutive words “cricket”.

    [5]
    View model solution

    PHP Program to Print Content Between Two Words in a File

    <?php
    $filename = "sport.txt";
    
    if (!file_exists($filename)) {
        die("File $filename does not exist.");
    }
    
    // Read entire file content into string
    $content = file_get_contents($filename);
    $keyword = "cricket";
    
    // Find first occurrence of "cricket" (case-insensitive)
    $firstPos = stripos($content, $keyword);
    
    if ($firstPos === false) {
        echo "Word '$keyword' not found in file.";
        exit;
    }
    
    // Offset index right after the first word
    $startPos = $firstPos + strlen($keyword);
    
    // Find second occurrence starting after the first
    $secondPos = stripos($content, $keyword, $startPos);
    
    if ($secondPos === false) {
        echo "Second occurrence of '$keyword' not found.";
        exit;
    }
    
    // Extract portion between the two words
    $portion = substr($content, $startPos, $secondPos - $startPos);
    
    echo "<h3>Portion between first two occurrences of '$keyword':</h3>";
    echo "<blockquote>" . nl2br(htmlspecialchars(trim($portion))) . "</blockquote>";
    ?>
    
  18. Validate a form having the following fields and validation conditions : Age – Text field (integer with range 1-100) Gender – Radio Button (Value : Either Male, Female or Other) Hobbies – Check boxes (Values : swimming, dancing and singing) The form must be submitted and validated on the same page where the form exists and the validation error messages are to be shown in an unordered list.

    [10]
    View model solution

    Self-Submitting Form with Validation and Error Reporting

    <?php
    $errors = [];
    $age = "";
    $gender = "";
    $hobbies = [];
    $isSubmitted = false;
    
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $isSubmitted = true;
        $age = trim($_POST["age"] ?? "");
        $gender = $_POST["gender"] ?? "";
        $hobbies = $_POST["hobbies"] ?? [];
    
        // 1. Age Validation: Integer between 1 and 100
        if ($age === "" || !filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 1, "max_range" => 100]])) {
            $errors[] = "Age must be a valid integer between 1 and 100.";
        }
    
        // 2. Gender Validation: Either Male, Female, or Other
        $allowedGenders = ["Male", "Female", "Other"];
        if (empty($gender) || !in_array($gender, $allowedGenders, true)) {
            $errors[] = "Please select a valid gender option (Male, Female, or Other).";
        }
    
        // 3. Hobbies Validation: Checkboxes (swimming, dancing, singing)
        $allowedHobbies = ["swimming", "dancing", "singing"];
        $invalidHobbies = array_diff($hobbies, $allowedHobbies);
        if (!empty($invalidHobbies)) {
            $errors[] = "Invalid hobby selected.";
        }
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
      <title>User Registration & Hobbies Form</title>
      <style>
        .error-box { background: #ffebee; border: 1px solid #f44336; color: #c62828; padding: 12px; border-radius: 6px; }
        .success-box { background: #e8f5e9; border: 1px solid #4caf50; color: #2e7d32; padding: 12px; border-radius: 6px; }
      </style>
    </head>
    <body>
      <h2>Student Information Form</h2>
    
      <!-- Error Messages in Unordered List -->
      <?php if ($isSubmitted && !empty($errors)): ?>
        <div class="error-box">
          <strong>Please correct the following errors:</strong>
          <ul>
            <?php foreach ($errors as $err): ?>
              <li><?= htmlspecialchars($err) ?></li>
            <?php endforeach; ?>
          </ul>
        </div>
      <?php elseif ($isSubmitted && empty($errors)): ?>
        <div class="success-box">
          <p>Form validated successfully!</p>
          <p>Age: <?= htmlspecialchars($age) ?> | Gender: <?= htmlspecialchars($gender) ?> | Hobbies: <?= implode(", ", array_map('htmlspecialchars', $hobbies)) ?></p>
        </div>
      <?php endif; ?>
    
      <form method="POST" action="">
        <p>
          <label>Age (1 - 100):</label><br>
          <input type="text" name="age" value="<?= htmlspecialchars($age) ?>">
        </p>
    
        <p>
          <label>Gender:</label><br>
          <label><input type="radio" name="gender" value="Male" <?= ($gender === 'Male') ? 'checked' : '' ?>> Male</label>
          <label><input type="radio" name="gender" value="Female" <?= ($gender === 'Female') ? 'checked' : '' ?>> Female</label>
          <label><input type="radio" name="gender" value="Other" <?= ($gender === 'Other') ? 'checked' : '' ?>> Other</label>
        </p>
    
        <p>
          <label>Hobbies:</label><br>
          <label><input type="checkbox" name="hobbies[]" value="swimming" <?= in_array('swimming', $hobbies) ? 'checked' : '' ?>> Swimming</label>
          <label><input type="checkbox" name="hobbies[]" value="dancing" <?= in_array('dancing', $hobbies) ? 'checked' : '' ?>> Dancing</label>
          <label><input type="checkbox" name="hobbies[]" value="singing" <?= in_array('singing', $hobbies) ? 'checked' : '' ?>> Singing</label>
        </p>
    
        <button type="submit">Submit & Validate</button>
      </form>
    </body>
    </html>
    
  19. Write short notes on : a. Here document. b. Inspecting file permission.

    [10]
    View model solution

    Short Notes

    a. Here Document (Heredoc) in PHP

    A Heredoc is a syntax for defining multi-line strings in PHP without requiring double quotes or manual concatenation. It behaves identically to double-quoted strings (variables and escape sequences are parsed and interpolated).

    <?php
    $user = "Kishor";
    $department = "BITM 4th Semester";
    
    // Heredoc syntax starting with <<<IDENTIFIER
    $htmlContent = <<<EOD
    <div class="profile-card">
        <h3>Welcome, $user!</h3>
        <p>Enrolled Department: $department</p>
    </div>
    EOD;
    
    echo $htmlContent;
    ?>
    
    • Rules: The closing identifier (EOD;) must appear on its own line.
    • Nowdoc: Similar to Heredoc but enclosed in single quotes (<<<'EOD'), behaving like single-quoted strings where no variable expansion takes place.

    b. Inspecting File Permissions in PHP

    PHP includes a suite of filesystem inspection functions:

    1. fileperms($filepath): Returns full numeric permission mask (including file type bits). To extract the standard Unix permission mode (like 0755 or 0644), mask with 0777:
      $mode = decoct(fileperms("secure_data.txt") & 0777);
      
    2. Boolean Capability Inspectors:
      • is_readable($path): Returns true if current web server process can read the file.
      • is_writable($path): Returns true if file exists and can be written to.
      • is_executable($path): Checks execution rights.