2079

BIT301 · TU past paper

Web Technology II 2079 question paper

The complete TU 2079 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 marksStatic variables and scopeAnswer

    What are variables? How can you define static variables? Write a PHP program to illustrate the use of Switch statement.[10]

    Variables, Static Variables & Switch Statement in PHP

    A. Variables in PHP

    A variable is a named container used to store data values that can be used and manipulated throughout a program.

    Key Rules for PHP Variables:

    • All variables begin with the $ sign followed by the variable name
    • Variable names must start with a letter or underscore (_)
    • Variable names cannot start with a number
    • Variable names are case-sensitive ($age and $Age are different)
    • PHP is a loosely typed language, so data types do not need to be declared explicitly

    Example:

    <?php
        $name  = "Alice";   // String variable
        $age   = 20;        // Integer variable
        $price = 49.99;     // Float variable
        echo $name;
        echo $age;
    ?>
    

    B. Static Variables

    A static variable is a local variable that retains its value between function calls instead of being destroyed when the function exits.

    Characteristics:

    • Declared using the keyword static before the variable name
    • Initialized only once (on the first function call)
    • On subsequent calls, it remembers its previous value
    • Commonly used for counters and state tracking

    Syntax:

    static $variable_name = value;
    

    Example:

    <?php
        function counter() {
            static $count = 0;   // initialized only once
            $count++;
            echo "Count = $count  ";
        }
    
        counter();   // Output: Count = 1
        counter();   // Output: Count = 2
        counter();   // Output: Count = 3
    ?>
    

    Here, $count is not reset to 0 on each call because it is declared as static. Without static, the output would always be Count = 1.


    C. PHP Program to Illustrate the Switch Statement

    The switch statement evaluates an expression and executes the matching case block. It is a cleaner alternative to multiple if...elseif...else chains.

    Syntax:

    switch (expression) {
        case value1:
            // code block
            break;
        case value2:
            // code block
            break;
        default:
            // code block
    }
    

    Program:

    <?php
        $day = 3;
    
        switch ($day) {
            case 1:
                echo "Monday";
                break;
            case 2:
                echo "Tuesday";
                break;
            case 3:
                echo "Wednesday";
                break;
            case 4:
                echo "Thursday";
                break;
            case 5:
                echo "Friday";
                break;
            case 6:
                echo "Saturday";
                break;
            case 7:
                echo "Sunday";
                break;
            default:
                echo "Invalid day number";
        }
    ?>
    

    Output:

    Wednesday
    

    Key Points about Switch:

    FeatureDescription
    breakStops execution and exits the switch block
    Without breakExecution falls through to the next case
    defaultExecutes when no matching case is found
    ComparisonUses loose comparison (==) between expression and cases

    Summary

    ConceptDescription
    VariableNamed container starting with $ to store data
    Static VariableLocal variable that persists its value across function calls
    Switch StatementMulti-branch control structure based on matching case values
  2. 210 marksExtract and compact functionsAnswer

    How can you store string type data in an array? Write a PHP program to illustrate use of extract and compact functions for conversion between arrays and variables.[10]

    --- In PHP, strings can be stored in arrays just like any other data type. PHP supports both indexed arrays and associative arrays for storing string data. - Each string is stored at a numeric index starting from 0. -

  3. 310 marksForm submission and event handlingAnswer

    Consider you have a login form having username, password fields, login and cancel buttons. Now, write a PHP program for implementing login event. The login should be redirected to home.php upon successful login button event. The cancel button should clear the form field values upon its submission.[10]

    Both buttons are submit buttons inside the same form, and each carries its own name. A browser posts only the button that was actually pressed, so the script can ask isset($POST['login']) or isset($POST['cancel']) and know which event it...

  4. 45 marksDatabase querying and SQL executionAnswer

    How can you query a database in PHP? [5]

    Querying a database from PHP always follows the same shape: open a connection to the server, hand it an SQL statement, and read back either a result set (for a SELECT) or a count of affected rows (for an INSERT, UPDATE or DELETE). Two ex...

  5. 55 marksForm data retrievalAnswer

    How can you retrieve the form data? Illustrate with example. [5]

    When a form is submitted the browser sends the field values to the server, and PHP unpacks them into superglobal arrays that are available in every scope without being declared. Superglobal Holds ------

  6. 65 marksError handling and error handlersAnswer

    What is error handler? Write a PHP program to show use of error handler to format and print errors. [5]

    Error handler in PHP

    An error handler is a function of your own that PHP calls whenever it raises a diagnostic, in place of printing its built in message. Instead of a raw grey line of text in the middle of a page, the handler receives the details as arguments and can format them, write them to a log, show a friendly message, or stop the script. It is registered with set_error_handler().

    set_error_handler("functionName");
    

    The handler is called with four useful arguments:

    ParameterDescription
    $errnoThe error level, one of the E_* constants
    $errstrThe message text
    $errfileThe file in which the error was raised
    $errlineThe line number in that file

    What it returns matters. Returning true tells PHP the error has been dealt with, so its own handler stays quiet; returning false lets the standard handler run as well, which is how you keep normal logging while adding your own formatting.

    A custom handler covers the diagnostics the engine raises, that is E_WARNING, E_NOTICE, E_DEPRECATED and the E_USER_* family. It is never invoked for E_ERROR, E_PARSE or the core and compile level errors, and it is not invoked for a thrown Exception or Error; those need try and catch, and a fatal fault needs register_shutdown_function() with error_get_last().

    A program that formats and prints errors

    <?php
    
    function myErrorHandler($errno, $errstr, $errfile, $errline)
    {
        $labels = [
            E_WARNING     => "Warning",
            E_NOTICE      => "Notice",
            E_DEPRECATED  => "Deprecated",
            E_USER_ERROR  => "User error",
            E_USER_WARNING=> "User warning",
            E_USER_NOTICE => "User notice",
        ];
        $label = $labels[$errno] ?? "Unknown";
    
        echo "<div style='border:2px solid #c00; padding:10px; background:#ffe6e6;'>";
        echo "<strong>" . $label . " caught</strong> ";
        echo "<b>Level:</b> " . (int) $errno . " ";
        echo "<b>Message:</b> " . htmlspecialchars($errstr, ENT_QUOTES, "UTF-8") . " ";
        echo "<b>File:</b> " . htmlspecialchars(basename($errfile), ENT_QUOTES, "UTF-8") . " ";
        echo "<b>Line:</b> " . (int) $errline . " ";
        echo "</div> ";
    
        if ($errno === E_USER_ERROR) {
            exit(1);   // PHP does not halt by itself once a handler is installed
        }
        return true;
    }
    
    set_error_handler("myErrorHandler");
    
    echo $undefinedVariable;            // PHP 8: E_WARNING, value 2
    
    include "nonexistent_file.php";     // E_WARNING, the file cannot be opened
    
    trigger_error("This is a custom user error.", E_USER_ERROR);   // 256
    

    The message text is passed through htmlspecialchars() before it is printed, and the numbers are cast to int, because an error string often quotes a value the visitor supplied and echoing it raw into a page would be a cross site scripting hole. Only the file's base name is shown, so the server's directory layout is not published.

    What the page shows

    +-----------------------------------------------------------+
    | Warning caught                                            |
    | Level: 2                                                  |
    | Message: Undefined variable $undefinedVariable            |
    | File: error_demo.php                                      |
    | Line: 30                                                  |
    +-----------------------------------------------------------+
    
    +-----------------------------------------------------------+
    | Warning caught                                            |
    | Level: 2                                                  |
    | Message: include(nonexistent_file.php): Failed to open    |
    |          stream: No such file or directory                |
    | File: error_demo.php                                      |
    | Line: 32                                                  |
    +-----------------------------------------------------------+
    
    +-----------------------------------------------------------+
    | User error caught                                         |
    | Level: 256                                                |
    | Message: This is a custom user error.                     |
    | File: error_demo.php                                      |
    | Line: 34                                                  |
    +-----------------------------------------------------------+
    

    Points worth noting

    Reading an undefined variable is an E_WARNING with the value 2 in PHP 8, not the E_NOTICE with the value 8 that PHP 5 and 7 produced, and the message now names the variable, as in "Undefined variable $undefinedVariable". A missing array key changed in the same way. A failed include raises two warnings, one from the failed open and one from the failed inclusion, so the handler fires twice for that single line.

    trigger_error() raises a diagnostic on purpose and is the usual way to test a handler. Once a custom handler is installed, PHP no longer stops the script on E_USER_ERROR, so the handler must call exit() itself if the run should end, which is why the example does so.

    A custom handler improves readability, keeps file paths and query fragments off a production page, and gives one place to add error_log(), so the same code can present a tidy message to the visitor and a complete record to the developer.

  7. 75 marksJSON file parsing and readingAnswer

    For the following JSON file named BIT.JSON, write a PHP program to read information from this JSON file: {Name: "Gunadi", Email: "[email protected]", Dob: "January 1", Age: 30} [5]

    The listing in the question is written as a JavaScript object literal, with the property names bare: That is not valid JSON, and jsondecode() rejects it and returns null, because the JSON grammar requires every key to be a double quoted ...

  8. 85 marksPHP comments and documentationAnswer

    How are comments written in PHP? Write a PHP program that will read your name and roll number and print the values. Label your program with appropriate comments. [5]

    PHP accepts three forms of comment, inherited from the languages it grew out of. Two are single line and one spans several lines, and none of them are sent to the browser: the parser strips them before any output is produced. Form Syntax...

  9. 95 marksString operations and concatenationAnswer

    Write a PHP program that will contain a concat string function. The function should have two arguments st1 and st2 of type string and should return st3 which is concatenation of st1 and st2. [5]

    Part Description ------------------- function concatString($st1, $st2) Defines a function with two string arguments st1 and st2 $st3 = $st1 . $st2 Uses the . (dot) operator to concatenate the two strings and stores in $st3 return

  10. 105 marksArray slicing with array_slice functionAnswer

    Write a PHP program to extract subset of a string array using array_slice() function. [5]

    arrayslice() is a built-in PHP function that extracts a portion (subset) of an array and returns it as a new array. Syntax: Parameter Description ------ array The input array start Starting index (0-based) length Number of elements to ex...

  11. 115 marksAnonymous classesAnswer

    Describe an anonymous class using suitable example. [5]

    An anonymous class is a class written directly at the place where its single object is needed, with no name attached to it. PHP creates the class and the object in one expression, new class { ... }, a form available since PHP 7. Before t...

  12. 125 marksSession creation and initializationAnswer

    Write a PHP program for illustrating the starting and ending of session. [5]

    HTTP has no memory, so two requests from the same visitor look unrelated to the server. A session gives them a thread: PHP generates a session id, sends it to the browser in a cookie, and keeps a matching store on the server. The