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.
Tap a question to open its answer.
- 110 marksStatic variables and scopeHideAnswer
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 (
$ageand$Ageare 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
staticbefore 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,
$countis not reset to 0 on each call because it is declared asstatic. Withoutstatic, the output would always beCount = 1.
C. PHP Program to Illustrate the Switch Statement
The switch statement evaluates an expression and executes the matching
caseblock. It is a cleaner alternative to multipleif...elseif...elsechains.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:
WednesdayKey Points about Switch:
Feature Description breakStops execution and exits the switch block Without breakExecution falls through to the next case defaultExecutes when no matching case is found Comparison Uses loose comparison ( ==) between expression and cases
Summary
Concept Description Variable Named container starting with $to store dataStatic Variable Local variable that persists its value across function calls Switch Statement Multi-branch control structure based on matching case values - All variables begin with the
- 210 marksExtract and compact functionsHideAnswer
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. -
- 310 marksForm submission and event handlingHideAnswer
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...
- 45 marksDatabase querying and SQL executionHideAnswer
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...
- 55 marksForm data retrievalHideAnswer
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 ------
- 65 marksError handling and error handlersHideAnswer
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:
Parameter Description $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
truetells PHP the error has been dealt with, so its own handler stays quiet; returningfalselets 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_DEPRECATEDand theE_USER_*family. It is never invoked forE_ERROR,E_PARSEor the core and compile level errors, and it is not invoked for a thrownExceptionorError; those needtryandcatch, and a fatal fault needsregister_shutdown_function()witherror_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); // 256The message text is passed through
htmlspecialchars()before it is printed, and the numbers are cast toint, 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_WARNINGwith the value 2 in PHP 8, not theE_NOTICEwith 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 failedincluderaises 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 onE_USER_ERROR, so the handler must callexit()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. - 75 marksJSON file parsing and readingHideAnswer
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 ...
- 85 marksPHP comments and documentationHideAnswer
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...
- 95 marksString operations and concatenationHideAnswer
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
- 105 marksArray slicing with array_slice functionHideAnswer
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...
- 115 marksAnonymous classesHideAnswer
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...
- 125 marksSession creation and initializationHideAnswer
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