Important Questions

BIT301 · Exam intelligence

Web Technology II important questions

From 5 past TU papers: which questions keep coming back, how much they carry, and what is most likely to show up next. Every question links to a model answer.

Most likely in the next examStatistical

Ranked by how often a topic is asked, its marks weight, and whether it is due after skipping the 2082 paper. No guarantees; study the whole syllabus.

1asked 4xavg 5 marks · Error handling and error handlers
Answer

What is the error handler? Write a program to demonstrate error handler function. [5]

Error Handler in PHP

Definition

An error handler is a user-defined function that is called automatically whenever a PHP error occurs. Instead of displaying the default PHP error messages, a custom error handler allows the programmer to control how errors are handled, such as logging them, displaying custom messages, or redirecting the user.

In PHP, the built-in function set_error_handler() is used to register a custom error handling function.


Syntax

set_error_handler("functionName");

The custom error handler function must accept the following parameters:

ParameterDescription
$errnoError number/level
$errstrError message
$errfileFile where error occurred
$errlineLine number where error occurred

Program to Demonstrate Error Handler

<?php

// Step 1: Define the custom error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "<b>Custom Error Handler Triggered!</b> ";
    echo "Error Number : " . $errno . " ";
    echo "Error Message: " . $errstr . " ";
    echo "Error File   : " . $errfile . " ";
    echo "Error Line   : " . $errline . " ";
    echo "<hr>";
}

// Step 2: Register the custom error handler
set_error_handler("myErrorHandler");

// Step 3: Trigger errors to test the handler

// Triggering a user-defined notice
trigger_error("This is a user notice!", E_USER_NOTICE);

// Triggering a user-defined warning
trigger_error("This is a user warning!", E_USER_WARNING);

// Triggering a division by zero warning
$a = 10;
$b = 0;
if ($b == 0) {
    trigger_error("Division by zero is not allowed!", E_USER_ERROR);
}

echo "Program continues after error handling.";

?>

Output

Custom Error Handler Triggered!
Error Number : 1024
Error Message: This is a user notice!
Error File   : /path/to/file.php
Error Line   : 20
---
Custom Error Handler Triggered!
Error Number : 512
Error Message: This is a user warning!
Error File   : /path/to/file.php
Error Line   : 23
---
Custom Error Handler Triggered!
Error Number : 256
Error Message: Division by zero is not allowed!
Error File   : /path/to/file.php
Error Line   : 28

Key Points

  • set_error_handler() overrides PHP's default error handling.
  • trigger_error() is used to manually generate an error for testing.
  • Common error constants: E_USER_NOTICE, E_USER_WARNING, E_USER_ERROR.
  • Custom error handlers help in debugging, logging, and providing user-friendly error messages.
2asked 2xavg 5 marks · due (skipped 2082) · Session creation and initialization
Answer

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...

3asked 2xavg 5 marks · due (skipped 2082) · Error reporting and configuration
Answer

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...

4asked 2xavg 5 marks · due (skipped 2082) · Conversion between arrays and variables
Answer

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.

5asked 2xavg 8 marks · due (skipped 2082) · Form data retrieval
Answer

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 ------ $GET Values from the query string,...

Most repeated questions

Topics asked at least twice, most-asked first.

asked 4xavg 5 marks · 2082, 2081, 2079, 0
Answer

What is the error handler? Write a program to demonstrate error handler function. [5]

Error Handler in PHP

Definition

An error handler is a user-defined function that is called automatically whenever a PHP error occurs. Instead of displaying the default PHP error messages, a custom error handler allows the programmer to control how errors are handled, such as logging them, displaying custom messages, or redirecting the user.

In PHP, the built-in function set_error_handler() is used to register a custom error handling function.


Syntax

set_error_handler("functionName");

The custom error handler function must accept the following parameters:

ParameterDescription
$errnoError number/level
$errstrError message
$errfileFile where error occurred
$errlineLine number where error occurred

Program to Demonstrate Error Handler

<?php

// Step 1: Define the custom error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "<b>Custom Error Handler Triggered!</b> ";
    echo "Error Number : " . $errno . " ";
    echo "Error Message: " . $errstr . " ";
    echo "Error File   : " . $errfile . " ";
    echo "Error Line   : " . $errline . " ";
    echo "<hr>";
}

// Step 2: Register the custom error handler
set_error_handler("myErrorHandler");

// Step 3: Trigger errors to test the handler

// Triggering a user-defined notice
trigger_error("This is a user notice!", E_USER_NOTICE);

// Triggering a user-defined warning
trigger_error("This is a user warning!", E_USER_WARNING);

// Triggering a division by zero warning
$a = 10;
$b = 0;
if ($b == 0) {
    trigger_error("Division by zero is not allowed!", E_USER_ERROR);
}

echo "Program continues after error handling.";

?>

Output

Custom Error Handler Triggered!
Error Number : 1024
Error Message: This is a user notice!
Error File   : /path/to/file.php
Error Line   : 20
---
Custom Error Handler Triggered!
Error Number : 512
Error Message: This is a user warning!
Error File   : /path/to/file.php
Error Line   : 23
---
Custom Error Handler Triggered!
Error Number : 256
Error Message: Division by zero is not allowed!
Error File   : /path/to/file.php
Error Line   : 28

Key Points

  • set_error_handler() overrides PHP's default error handling.
  • trigger_error() is used to manually generate an error for testing.
  • Common error constants: E_USER_NOTICE, E_USER_WARNING, E_USER_ERROR.
  • Custom error handlers help in debugging, logging, and providing user-friendly error messages.
asked 2xavg 5 marks · 2081, 2079
Answer

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...

asked 2xavg 5 marks · 2081, 2080
Answer

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...

asked 2xavg 5 marks · 2081, 0
Answer

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.

asked 2xavg 8 marks · 2079, 0
Answer

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 ------ $GET Values from the query string,...

asked 2xavg 5 marks · 2079, 0
Answer

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 $st3 Re...

asked 2xavg 5 marks · 2082, 2080
Answer

How can you handle cookies and sessions? Illustrate with examples. [5]

Note: The reference notes did not contain material on this topic. The following answer is based on standard PHP web development curriculum as taught in BSc CSIT. --- A cookie is a small piece of data stored on the client's browser by the...

asked 2xavg 5 marks · 2082, 2079
Answer

What is anonymous class? Write a program to demonstrate the use of anonymous classes. [5]

Anonymous classes in PHP

An anonymous class is a class that is defined and instantiated in a single expression and is never given a name. PHP has supported them since version 7, written as new class { ... }. The value of the expression is an object, so the definition and the object creation happen together, which suits a case where an implementation is needed exactly once and a named class kept in its own file would only add noise.

An anonymous class is an ordinary class in every other respect. It may accept constructor arguments, may extend one class, may implement any number of interfaces, and may use traits. Two anonymous classes written at two different places in the code are always distinct classes even when their bodies are identical, and because the class has no name it cannot be referred to, extended or reused elsewhere.

The general form is:

$object = new class ($constructorArguments) extends SomeClass implements SomeInterface {
    // properties and methods
};

A program that uses one

<?php
interface Logger
{
    public function log(string $message): void;
}

class Report
{
    private Logger $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function run(string $title): void
    {
        // the title may come from $_GET, so it is escaped before it is written to the
        // page, otherwise a title containing a script tag would run in the browser
        echo "<h3>" . htmlspecialchars($title, ENT_QUOTES, "UTF-8") . "</h3>";
        $this->logger->log("The report " . $title . " was generated.");
    }
}

// an anonymous class supplying a one off implementation of the Logger interface
$report = new Report(new class implements Logger {
    public function log(string $message): void
    {
        echo "<p>LOG: " . htmlspecialchars($message, ENT_QUOTES, "UTF-8") . "</p>";
    }
});

$report->run("Monthly sales");

// an anonymous class that takes a constructor argument of its own
$counter = new class (10) {
    public function __construct(private int $value) {}

    public function next(): int
    {
        return ++$this->value;
    }
};

echo "<p>Next value: " . $counter->next() . "</p>";
?>

The browser receives the heading Monthly sales, then the line LOG: The report Monthly sales was generated., and finally Next value: 11.

What the example shows

FeatureIn the example
Defined and created togethernew class implements Logger { ... }
Implements an interfaceSatisfies the Logger type that Report demands
Takes constructor argumentsnew class (10) { ... } passes 10 to __construct()
Has no nameNothing else in the program can refer to either class

Anonymous classes are used for test doubles, for small strategy or callback objects, and for adapters that exist only to satisfy a type hint. A closure would serve when only one piece of behaviour is needed, but an anonymous class is the right tool when the interface being satisfied has several methods or when the object must carry state between calls.

asked 2xavg 5 marks · 2082, 0
Answer

Write a program to parse a CSV file and display the content in the file. [5]

Reading a CSV file and displaying its contents

A CSV file stores a table as plain text: one record per line, with the fields of a record separated by commas and any field that itself contains a comma or a quote wrapped in double quotes. Because of that quoting rule a CSV line cannot be split reliably by hand, so PHP supplies fgetcsv(), which reads one record from an open file and returns its fields as an array with the quoting already resolved.

Take the file data.csv:

Name,Age,City
Alice,23,Kathmandu
Bob,25,Pokhara
Charlie,22,Lalitpur

The script reads the first record as the list of column names, pairs each later record with those names using array_combine(), and prints the result.

<?php
$filename = "data.csv";

if (!is_readable($filename)) {
    exit("The CSV file could not be read.");
}

$handle = fopen($filename, "r");
if ($handle === false) {
    exit("Unable to open the CSV file.");
}

$header = fgetcsv($handle, 0, ",");
if ($header === false) {
    fclose($handle);
    exit("The CSV file is empty.");
}

echo "<table border='1'><tr>";
foreach ($header as $column) {
    // file contents are untrusted, so they are escaped before reaching the page,
    // otherwise a field containing markup would be interpreted by the browser
    echo "<th>" . htmlspecialchars((string) $column, ENT_QUOTES, "UTF-8") . "</th>";
}
echo "</tr>";

$count = 0;

while (($row = fgetcsv($handle, 0, ",")) !== false) {

    if ($row === array(null)) {              // ignore a blank line
        continue;
    }

    if (count($row) !== count($header)) {    // a malformed record, report and skip it
        echo "<tr><td colspan='" . count($header) . "'>Skipped a record with the wrong number of fields.</td></tr>";
        continue;
    }

    $record = array_combine($header, $row);  // field name to field value

    echo "<tr>";
    foreach ($record as $value) {
        echo "<td>" . htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8") . "</td>";
    }
    echo "</tr>";

    $count++;
}

echo "</table>";
fclose($handle);

echo "<p>Total records read: " . $count . "</p>";
?>

What the page shows

NameAgeCity
Alice23Kathmandu
Bob25Pokhara
Charlie22Lalitpur

followed by the line Total records read: 3.

Functions used

FunctionPurpose
fopen($file, "r")Opens the file for reading and returns a handle
fgetcsv($handle, 0, ",")Reads the next record and returns its fields as an array
array_combine($keys, $values)Builds an associative record from the header names and the field values
fclose($handle)Closes the file when the loop ends
str_getcsv($line)Parses a single CSV line already held in a string

Because $record is keyed by column name, a particular field can be printed directly, for example htmlspecialchars($record["City"], ENT_QUOTES, "UTF-8"), without depending on the position of that column in the file. That makes the script survive a reordering of the columns, which a program indexing by $row[2] would not.

Two points decide whether such a script is correct in practice. The record must be read with fgetcsv() or str_getcsv() rather than explode(",", $line), because the quoting rule means a comma inside a quoted field is data and not a separator. And every value taken from the file must pass through htmlspecialchars() before it is echoed, since the file is input from outside the program and an unescaped field is a stored cross site scripting hole in the page that displays it.

asked 2xavg 5 marks · 2082, 0
Answer

Write a program to create a class Employee with some attributes and methods. Create an object of the class and display some output using any method in the class. [5]

An Employee class in PHP

A class is the blueprint that describes what an employee record holds and what can be done with it, and an object is one concrete employee built from that blueprint. In PHP the properties are declared with a visibility keyword, the constructor is the magic method __construct(), and inside any method the current object is referred to as $this, with -> used to reach a property or call a method.

<?php
class Employee
{
    private int    $id;
    private string $name;
    private string $department;
    private float  $salary;      // monthly salary

    public function __construct(int $id, string $name, string $department, float $salary)
    {
        $this->id         = $id;
        $this->name       = $name;
        $this->department = $department;
        $this->salary     = $salary;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function annualSalary(): float
    {
        return $this->salary * 12;
    }

    public function giveRaise(float $percent): void
    {
        $this->salary += ($this->salary * $percent) / 100;
    }

    public function display(): string
    {
        // the name and department are stored values that end up inside an HTML page,
        // so they are escaped here, since a value held in the database may contain
        // characters such as < or & that would otherwise be read as markup
        $safeName = htmlspecialchars($this->name, ENT_QUOTES, "UTF-8");
        $safeDept = htmlspecialchars($this->department, ENT_QUOTES, "UTF-8");

        return "<p>Employee ID: " . $this->id . " "
             . "Name: " . $safeName . " "
             . "Department: " . $safeDept . " "
             . "Monthly salary: Rs. " . number_format($this->salary, 2) . "</p>";
    }
}

// creating an object of the class
$emp = new Employee(101, "Ram Sharma", "IT", 50000);

echo $emp->display();
echo "<p>Annual salary: Rs. " . number_format($emp->annualSalary(), 2) . "</p>";

$emp->giveRaise(10);
echo "<p>After a 10 percent raise:</p>";
echo $emp->display();
?>

The page produced is:

Employee ID: 101
Name: Ram Sharma
Department: IT
Monthly salary: Rs. 50,000.00

Annual salary: Rs. 600,000.00

After a 10 percent raise:
Employee ID: 101
Name: Ram Sharma
Department: IT
Monthly salary: Rs. 55,000.00

The parts of the class

PartRole
class Employee { ... }Declares the blueprint
private int $id and the other threeThe attributes, hidden from outside code
__construct()Runs automatically at new and fills the attributes
$thisThe object the method is currently working on
annualSalary(), giveRaise(), display()The methods, the behaviour of the object
new Employee(101, "Ram Sharma", "IT", 50000)Creates one object from the blueprint

Declaring the attributes private is what makes giveRaise() worth writing: outside code cannot reach in and set an arbitrary salary, it must go through a method that applies the rule. PHP 8 allows the same class to be written more briefly with constructor property promotion, where public function __construct(private int $id, private string $name) declares and assigns the properties in one line.

Study every one of these with model answers, flashcards, and MCQs.

Open BIT301 study modes