2081

BIT301 · TU past paper

Web Technology II 2081 question paper

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

Past Papers2082208120802079

Tap a question to open its answer.

  1. 110 marksServer side scripting conceptsAnswer

    What is server side scripting? How can you define and declare variables in PHP? Write PHP programs to demonstrate concepts of while and do while loops.[10]

    Server Side Scripting, PHP Variables, and Loops


    Part A: Server Side Scripting

    Server side scripting is a technique used in web development where scripts are executed on the web server rather than on the client's browser. The server processes the script, generates output (usually HTML), and sends only the final result to the client. The user cannot view the original source code.

    How it works:

    1. The client sends a request to the server (e.g., requesting a .php file)
    2. The web server identifies the script and passes it to the appropriate interpreter (e.g., PHP interpreter)
    3. The interpreter executes the code, interacts with databases if needed, and produces HTML output
    4. The server sends this HTML response back to the client's browser

    Examples of server side scripting languages: PHP, Python (Django/Flask), ASP.NET, Node.js, JSP

    Advantages:

    • Dynamic web page generation
    • Database interaction is possible
    • Source code is hidden from the client
    • Supports user authentication, session management, etc.

    Part B: Defining and Declaring Variables in PHP

    PHP is a loosely typed language, meaning there is no need to explicitly declare the data type of a variable. Variables are declared using the dollar sign ($) followed by the variable name.

    Rules for declaring variables:

    • Must start with $ followed by the variable name
    • Variable name must begin with a letter or underscore (not a digit)
    • Variable names are case-sensitive ($Age and $age are different)
    • No data type declaration is required; PHP assigns it automatically

    Example:

    <?php
        $name      = "John";   // String variable
        $age       = 25;       // Integer variable
        $price     = 99.5;     // Float variable
        $is_active = true;     // Boolean variable
    
        echo $name . " ";
        echo $age;
    ?>
    

    Variable Scopes in PHP:

    ScopeDescription
    LocalDeclared inside a function; accessible only within that function
    GlobalDeclared outside a function; accessible outside (use global keyword inside functions)
    StaticRetains its value even after the function finishes executing

    Part C: While Loop in PHP

    The while loop is an entry-controlled loop. The condition is checked before executing the loop body. If the condition is false initially, the loop body never executes.

    Syntax:

    while (condition) {
        // code to execute
    }
    

    Program: Print numbers 1 to 5 using while loop

    <?php
        $i = 1;
        while ($i <= 5) {
            echo "Number: " . $i . " ";
            $i++;
        }
    ?>
    

    Output:

    Number: 1
    Number: 2
    Number: 3
    Number: 4
    Number: 5
    

    Part D: Do-While Loop in PHP

    The do-while loop is an exit-controlled loop. The loop body is executed at least once, and then the condition is checked. If the condition is true, the loop continues.

    Syntax:

    do {
        // code to execute
    } while (condition);
    

    Program: Print numbers 1 to 5 using do-while loop

    <?php
        $i = 1;
        do {
            echo "Number: " . $i . " ";
            $i++;
        } while ($i <= 5);
    ?>
    

    Output:

    Number: 1
    Number: 2
    Number: 3
    Number: 4
    Number: 5
    

    Key Difference: While vs Do-While

    FeatureWhile LoopDo-While Loop
    TypeEntry-controlledExit-controlled
    Condition checkBefore loop bodyAfter loop body
    Minimum executions0 times (if condition is false)At least 1 time
    Semicolon after conditionNot requiredRequired (; after while)

    Conclusion

    Server side scripting enables dynamic web content generation on the server. PHP provides simple variable declaration using $ with no type declaration needed. The while loop checks the condition before execution (entry-controlled), while the do-while loop guarantees at least one execution by checking the condition after the loop body (exit-controlled).

  2. 210 marksGlobal variables and scopeAnswer

    How can you define and declare functions? Differentiate global variable from static variable. Write a PHP program to demonstrate the use of global and static variables.[10]

    --- A function is a block of reusable code that performs a specific task. In PHP, functions are defined using the function keyword. - Function names are case-insensitive - Function names must start with a letter or underscore - Parameter...

  3. 310 marksPHP Data Objects and PDOAnswer

    What is a PHP Data Object? How does MySQLi Object Interface work? Write a PHP program to read data elements from a database table and display in a page.[10]

    PDO, the MySQLi object interface, and reading a table into a page

    PHP Data Objects

    PDO is a database access layer that gives PHP one uniform, object oriented interface over many database engines: MySQL and MariaDB, PostgreSQL, SQLite, SQL Server, Oracle and others. The engine is named only in the DSN, the connection string, so moving an application from MySQL to PostgreSQL changes that one line rather than every call in the program.

    Its strengths are worth naming. It is driver independent. It supports prepared statements with named placeholders, which keeps a statement readable when it carries five or six values. It can be told to report every failure as an exception, so a mistyped query cannot pass unnoticed. And with ATTR_EMULATE_PREPARES set to false, placeholders really are sent to the server as placeholders, rather than being substituted by the driver in PHP first.

    <?php
    $pdo = new PDO(
        'mysql:host=localhost;dbname=college;charset=utf8mb4',
        'root',
        '',
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES   => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );
    
    $stmt = $pdo->prepare('SELECT id, name, age, email FROM students WHERE age >= :age');
    $stmt->execute([':age' => 20]);
    $students = $stmt->fetchAll();
    
    PDOMySQLi
    Databases supportedTwelve driversMySQL and MariaDB only
    API styleObject oriented onlyObject oriented and procedural
    Prepared statementsYesYes
    Named placeholdersYesNo, positional ? only
    Binding a valueexecute([...]) or bindValue()bind_param() with a type string

    Both are safe extensions and either is a correct choice. What matters far more than the choice between them is that user supplied values are bound rather than pasted into the SQL text.

    How the MySQLi object interface works

    MySQLi exposes the same functionality twice, as procedural functions and as objects. In the object interface the connection is an instance of mysqli, a query returns an instance of mysqli_result, and a prepared statement is an instance of mysqli_stmt. The work is then done by calling methods on those objects and reading their properties.

    The connection object is created with the host, user, password and database name, and it is worth switching error reporting on first so that a failure raises an exception instead of returning false and letting the script continue:

    <?php
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
    $conn = new mysqli('localhost', 'root', '', 'college');
    $conn->set_charset('utf8mb4');
    

    Calling $conn->query($sql) on a statement whose text is fixed returns a result object, and that object is asked for its rows, one at a time with fetch_assoc() or all at once with fetch_all(MYSQLI_ASSOC), and for how many there are through the num_rows property. When any part of the statement comes from the request, $conn->prepare($sql) returns a statement object instead, bind_param() attaches the values with a type string (s string, i integer, d float, b blob), execute() runs it and get_result() hands back the same kind of result object:

    <?php
    $stmt = $conn->prepare('SELECT id, name, age, email FROM students WHERE age >= ?');
    $stmt->bind_param('i', $minimumAge);
    $stmt->execute();
    $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    MemberWhat it gives you
    new mysqli(host, user, pass, db)The connection object
    $conn->connect_errorThe failure message, if the connection could not be made
    $conn->query($sql)Runs a fixed statement, returns a mysqli_result
    $conn->prepare($sql)Compiles a statement with ? placeholders, returns a mysqli_stmt
    $stmt->bind_param(), $stmt->execute()Supplies the values and runs the statement
    $result->num_rowsNumber of rows in the result set
    $result->fetch_assoc(), $result->fetch_all()Reads rows as associative arrays
    $conn->affected_rows, $conn->insert_idThe effect of a write
    $result->free(), $conn->close()Releases the result set and the connection

    Reading a table and displaying it

    The program assumes a database college with a table of students.

    CREATE DATABASE college CHARACTER SET utf8mb4;
    USE college;
    
    CREATE TABLE students (
        id    INT AUTO_INCREMENT PRIMARY KEY,
        name  VARCHAR(100),
        age   INT,
        email VARCHAR(100)
    );
    
    INSERT INTO students (name, age, email) VALUES
    ('Ram Sharma',  20, '[email protected]'),
    ('Sita Thapa',  22, '[email protected]'),
    ('Hari Poudel', 21, '[email protected]');
    

    The page finishes all its database work first and only then writes HTML, which keeps the two concerns apart and leaves the script free to send a header if it needs to.

    <?php
    // read_students.php
    declare(strict_types=1);
    
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
    $conn = new mysqli('localhost', 'root', '', 'college');
    $conn->set_charset('utf8mb4');
    
    $result   = $conn->query('SELECT id, name, age, email FROM students ORDER BY id');
    $students = $result->fetch_all(MYSQLI_ASSOC);
    $result->free();
    $conn->close();
    
    function e(?string $v): string
    {
        return htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Student records</title>
        <style>
            body  { font-family: Arial, sans-serif; margin: 30px; }
            table { border-collapse: collapse; width: 70%; }
            th, td { border: 1px solid #aaa; padding: 10px; text-align: left; }
            th    { background: #4CAF50; color: #fff; }
            tr:nth-child(even) { background: #f2f2f2; }
        </style>
    </head>
    <body>
    
    <h2>Student records from the database</h2>
    
    <?php if ($students): ?>
        <table>
            <tr><th>ID</th><th>Name</th><th>Age</th><th>Email</th></tr>
            <?php foreach ($students as $row): ?>
                <tr>
                    <td><?= (int) $row['id'] ?></td>
                    <td><?= e($row['name']) ?></td>
                    <td><?= (int) $row['age'] ?></td>
                    <td><?= e($row['email']) ?></td>
                </tr>
            <?php endforeach; ?>
        </table>
    <?php else: ?>
        <p>No records found in the students table.</p>
    <?php endif; ?>
    
    </body>
    </html>
    

    Every text column is printed through htmlspecialchars() and the numeric ones are cast to int. A value that came out of the database is not trustworthy simply because it was stored: a name typed as <script>alert(1)</script> would run in the browser of everyone who loaded this page if it were echoed raw, which is stored cross site scripting.

    In summary

    PDO is the portable extension, one object oriented API in front of many database drivers, with named placeholders and exceptions. MySQLi is MySQL specific and exposes the same work through a connection object, a result object and a statement object, whose methods do the querying and fetching. The program above uses that object interface end to end, running a fixed SELECT through query(), reading the rows with fetch_all(), and escaping every value on the way into the page. As soon as the page grows a filter that the visitor supplies, the query() call becomes a prepare() with a bound parameter, because a value from the request must never become part of the query text.

  4. 45 marksInterfaces and class differencesAnswer

    How is class different from interface? Illustrate with an example. [5]

    A class is a complete blueprint: it declares what an object holds and supplies the bodies of the methods that act on it. An interface is only a contract: it names the methods an implementing class must provide, without saying how any of ...

  5. 55 marksSession creation and initializationAnswer

    What is a session? How can you handle sessions in PHP? [5]

    A session is a way to store information (in variables) to be used across multiple pages of a website. Unlike cookies, session data is stored on the server side. Each user gets a unique session ID which is used to identify and retrieve th...

  6. 65 marksError handling and error handlersAnswer

    Define error handlers and error logs with examples. [5]

    Error handlers and error logs in PHP

    A running PHP script reports trouble in two different ways, and the two words in this question name the two halves of the response to it. An error handler decides what happens at the moment something goes wrong, while an error log is the permanent written record that lets a developer find out afterwards what went wrong on a live server, where the message is deliberately hidden from the visitor.

    Error handler

    An error handler is a function that PHP calls instead of printing its own diagnostic message, registered with set_error_handler(). The handler receives the error number, the message, the file and the line, and it can format the message, log it, show a friendly page, or stop the script.

    <?php
    function myErrorHandler($errno, $errstr, $errfile, $errline) {
        echo "<p class='err'>[" . $errno . "] "
           . htmlspecialchars($errstr, ENT_QUOTES, "UTF-8")
           . " in " . htmlspecialchars(basename($errfile), ENT_QUOTES, "UTF-8")
           . " on line " . (int) $errline . "</p>";
        return true;   // true means PHP's own handler must not run as well
    }
    
    set_error_handler("myErrorHandler");
    
    echo $test;   // PHP 8: Warning, Undefined variable $test
    

    The message is escaped with htmlspecialchars() before it is printed, because an error string can contain a value the visitor supplied and printing it raw would be a cross site scripting hole. Note the level too: since PHP 8.0 reading an undefined variable is an E_WARNING, not the E_NOTICE it was in PHP 5 and 7, and reading a missing array key is a warning as well.

    A custom handler only sees the diagnostics PHP raises: E_WARNING, E_NOTICE, E_DEPRECATED, the E_USER_* family and so on. It is never called for E_ERROR, E_PARSE or the core and compile level errors, and it is not called for exceptions. To report a genuine fatal error you add a shutdown function:

    register_shutdown_function(function () {
        $e = error_get_last();
        if ($e !== null && ($e["type"] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR))) {
            error_log("FATAL: " . $e["message"] . " in " . $e["file"] . ":" . $e["line"]);
        }
    });
    

    The second half of handling is try and catch, and PHP 8 makes one point here that is easy to get wrong. Dividing by zero no longer emits a warning: it throws DivisionByZeroError, and that class descends from Error, not from Exception. A catch (Exception $e) block therefore does not catch it. Catch the specific class, or catch Throwable, which is the common ancestor of both branches.

    try {
        $result = 10 / 0;
    } catch (DivisionByZeroError $e) {          // catch (Exception $e) would MISS this
        echo "Caught: " . $e->getMessage();     // Division by zero
    } finally {
        echo "Execution continues.";
    }
    

    Error log

    An error log is the file, or the system log, in which PHP writes the same diagnostics instead of showing them. On a production site the visitor should see nothing but a polite message, while the developer still needs the file name, the line and the time, so logging is switched on and display is switched off.

    display_errors = Off
    log_errors     = On
    error_log      = /var/log/php_errors.log
    

    The same settings can be made from a script with ini_set(), and error_log() writes a message of your own into whichever destination is configured.

    ini_set("log_errors", "1");
    ini_set("error_log", "/var/log/php_errors.log");
    
    error_log("Database connection failed in the login module for user id 42.");
    

    Each entry is stamped with the date and time, the severity and the position, so the file reads like this:

    [27-Jun-2026 10:35:22 UTC] PHP Warning:  Undefined variable $test in /var/www/index.php on line 15
    [27-Jun-2026 10:36:01 UTC] PHP Fatal error:  Uncaught DivisionByZeroError: Division by zero in /var/www/calc.php:8
    [27-Jun-2026 10:36:01 UTC] Database connection failed in the login module for user id 42.
    

    Never log a password, a session id or a card number: the log is a plain file that operations staff and backups can read.

    How the two differ

    FeatureError handlerError log
    When it actsAt the instant the error is raisedAfter the fact, as a record
    Registered or set byset_error_handler(), try/catchlog_errors, error_log in php.ini
    AudienceThe visitor and the running scriptThe developer and the administrator
    Effect on flowCan format, recover, redirect or stopNone, it only records

    In practice a good script uses both together: the handler keeps the page working and shows nothing sensitive, and the log keeps the evidence needed to fix the cause.

  7. 75 marksFile reading operationsAnswer

    Write a PHP program to read a file. [5]

    --- There are several ways to read a file in PHP. Below are the common approaches: --- --- --- --- Function Description ------ fopen($file, "r") Opens a file in read mode fgets($file) Reads one line from the file feof(

  8. 85 marksError reporting and configurationAnswer

    Describe the concepts of display_errors, variables_order and request_order in PHP.ini Settings. [5]

    These three directives in php.ini control what a PHP script says when something goes wrong and which request data the engine hands it in the first place. The first is an error visibility setting; the other two decide which superglobals g...

  9. 95 marksAnswer

    Describe the date time functions with examples. [5]

    Date and Time Functions in SQL

    Note: The reference notes did not contain this topic, so the answer is based on standard SQL/database curriculum covered in TU BSc CSIT.


    Date and Time Functions

    Date and time functions are built-in SQL functions used to perform operations on date and time values such as retrieving the current date/time, extracting parts of a date, and performing date arithmetic.


    Commonly Used Date and Time Functions

    1. NOW()

    Returns the current date and time.

    SELECT NOW();
    -- Output: 2024-05-15 10:30:45
    

    2. CURDATE() / CURRENT_DATE()

    Returns the current date (without time).

    SELECT CURDATE();
    -- Output: 2024-05-15
    

    3. CURTIME() / CURRENT_TIME()

    Returns the current time (without date).

    SELECT CURTIME();
    -- Output: 10:30:45
    

    4. DATE()

    Extracts only the date part from a datetime expression.

    SELECT DATE('2024-05-15 10:30:45');
    -- Output: 2024-05-15
    

    5. YEAR(), MONTH(), DAY()

    Extracts the year, month, or day from a date.

    SELECT YEAR('2024-05-15');   -- Output: 2024
    SELECT MONTH('2024-05-15');  -- Output: 5
    SELECT DAY('2024-05-15');    -- Output: 15
    

    6. DATEDIFF()

    Returns the difference in days between two dates.

    SELECT DATEDIFF('2024-05-15', '2024-01-01');
    -- Output: 135
    

    7. DATE_ADD() and DATE_SUB()

    Adds or subtracts a time interval from a date.

    SELECT DATE_ADD('2024-05-15', INTERVAL 10 DAY);
    -- Output: 2024-05-25
    
    SELECT DATE_SUB('2024-05-15', INTERVAL 1 MONTH);
    -- Output: 2024-04-15
    

    8. DATE_FORMAT()

    Formats a date value according to a specified format.

    SELECT DATE_FORMAT('2024-05-15', '%d/%m/%Y');
    -- Output: 15/05/2024
    

    Summary Table

    FunctionPurpose
    NOW()Current date and time
    CURDATE()Current date only
    CURTIME()Current time only
    DATEDIFF()Difference between two dates
    DATE_ADD()Add interval to a date
    DATE_FORMAT()Format a date value

    These functions are widely used in database applications for tasks like calculating age, finding records within a date range, and formatting date output for reports.

  10. 105 marksConstructors and initializationAnswer

    Write a PHP program to demonstrate use of constructor. [5]

    A constructor is a special method in a class that is automatically called when an object is created. In PHP, the constructor method is defined using construct(). --- --- --- Feature Description ------ construct() Special method called au...

  11. 115 marksConversion between arrays and variablesAnswer

    How conversion between arrays and variables is done using extract() and compact() functions? [5]

    Conversion Between Arrays and Variables: extract() and compact()


    1. extract() Function

    The extract() function converts an associative array into individual variables. Each key of the array becomes a variable name, and the corresponding value becomes the variable's value.

    Syntax

    extract(array, extract_rules, prefix);
    

    Example

    <?php
    $data = array("name" => "Ram", "age" => 21, "city" => "Kathmandu");
    
    extract($data);
    
    echo $name;   // Output: Ram
    echo $age;    // Output: 21
    echo $city;   // Output: Kathmandu
    ?>
    

    How it works:

    • Key "name" → variable $name = "Ram"
    • Key "age" → variable $age = 21
    • Key "city" → variable $city = "Kathmandu"

    2. compact() Function

    The compact() function does the opposite of extract(). It takes individual variables and converts them into an associative array. The variable names become the keys and their values become the array values.

    Syntax

    compact(var1, var2, ...);
    

    Example

    <?php
    $name = "Sita";
    $age  = 22;
    $city = "Pokhara";
    
    $result = compact("name", "age", "city");
    
    print_r($result);
    ?>
    

    Output:

    Array
    (
        [name] => Sita
        [age]  => 22
        [city] => Pokhara
    )
    

    How it works:

    • Variable $name → key "name" with value "Sita"
    • Variable $age → key "age" with value 22
    • Variable $city → key "city" with value "Pokhara"

    3. Relationship Between extract() and compact()

    Featureextract()compact()
    DirectionArray → VariablesVariables → Array
    InputAssociative arrayVariable names (as strings)
    OutputIndividual variablesAssociative array
    Use caseUnpacking array dataPacking variables into array

    4. Combined Example

    <?php
    // Using compact() to create array
    $roll = 101;
    $subject = "PHP";
    $marks = 85;
    
    $student = compact("roll", "subject", "marks");
    // $student = ["roll"=>101, "subject"=>"PHP", "marks"=>85]
    
    // Using extract() to get variables back
    extract($student);
    
    echo $roll;     // Output: 101
    echo $subject;  // Output: PHP
    echo $marks;    // Output: 85
    ?>
    

    Summary: extract() and compact() are complementary PHP functions used to easily convert between associative arrays and individual variables, making data handling more flexible and convenient.

  12. 125 marksString exploding and implodingAnswer

    What is exploding and imploding of strings? Illustrate with an example. [5]

    Exploding and Imploding of Strings in PHP


    1. Exploding a String

    Exploding means splitting a string into an array based on a specified delimiter/separator. In PHP, this is done using the built-in explode() function.

    Syntax:

    explode(separator, string, limit)
    
    • separator - the delimiter used to split the string (required)
    • string - the input string to be split (required)
    • limit - maximum number of elements in the array (optional)

    Example:

    <?php
        $str = "Apple,Banana,Mango,Orange";
        $fruits = explode(",", $str);
    
        print_r($fruits);
    ?>
    

    Output:

    Array
    (
        [0] => Apple
        [1] => Banana
        [2] => Mango
        [3] => Orange
    )
    

    Here, the string is split at every comma , and each part becomes an element of the array.


    2. Imploding a String

    Imploding means joining array elements into a single string using a specified separator/glue. In PHP, this is done using the built-in implode() function (also called join()).

    Syntax:

    implode(separator, array)
    
    • separator - the string placed between each array element (required)
    • array - the array whose elements are to be joined (required)

    Example:

    <?php
        $fruits = array("Apple", "Banana", "Mango", "Orange");
        $str = implode(" - ", $fruits);
    
        echo $str;
    ?>
    

    Output:

    Apple - Banana - Mango - Orange
    

    Here, the array elements are joined together with - as the separator to form a single string.


    Summary Table

    Featureexplode()implode()
    PurposeSplits a string into an arrayJoins an array into a string
    InputStringArray
    OutputArrayString
    Also known asSplitJoin

    Key Point: explode() and implode() are inverse operations of each other. Explode breaks a string apart; implode brings array pieces together.