Chapter 1
Web Technology II
TU BIT past exam questions
Past questions and answers
48 questions set from this chapter. Most repeated first.
- 2079 · 10 marks
What are variables? How can you define static variables? Write a PHP program to illustrate the use of Switch statement.
Answer
Variables. A variable in PHP is a named storage location for a value. It starts with $, followed by a letter or underscore, and is case-sensitive ($name and $Name differ). PHP is loosely typed, so a variable takes its type from the value assigned and needs no declaration.
$name = "Ram"; // string
$age = 20; // integer
$gpa = 3.6; // float
Static variables. A static variable is declared inside a function with the static keyword. It keeps its value between calls instead of being reset. It is initialised only once.
<?php
function counter() {
static $count = 0; // initialised only on the first call
$count++;
echo "Called $count time(s)<br>";
}
counter(); // 1
counter(); // 2
counter(); // 3
?>
Switch statement. switch compares one expression with several case values. break stops fall-through, and default runs when nothing matches.
<?php
$day = 3;
switch ($day) {
case 1: echo "Sunday"; break;
case 2: echo "Monday"; break;
case 3: echo "Tuesday"; break;
case 4: echo "Wednesday"; break;
default: echo "Invalid day";
}
?>
Output: Tuesday.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
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.
Answer
Storing strings in an array. A string is stored as an array element. Use the [] syntax or the array() constructor, as an indexed or an associative array.
$fruits = ["Apple", "Mango", "Banana"]; // indexed
$fruits[] = "Orange"; // append
$student = ["name" => "Sita", "city" => "Pokhara"]; // associative
str_split() or explode() can also break one string into an array of strings.
compact() and extract()
compact()builds an associative array from variables. The variable names become the keys.extract()does the reverse. Each array key becomes a variable holding its value.
<?php
$name = "Hari";
$age = 21;
$city = "Kathmandu";
// variables -> array
$arr = compact('name', 'age', 'city');
print_r($arr);
// Array ( [name] => Hari [age] => 21 [city] => Kathmandu )
// array -> variables
$data = ["title" => "PHP", "price" => 500];
extract($data);
echo "$title costs Rs $price"; // PHP costs Rs 500
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
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.
Answer
<?php
// login.php
$error = "";
$username = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (isset($_POST['cancel'])) {
// Cancel: clear all form fields
$username = "";
} elseif (isset($_POST['login'])) {
$username = trim($_POST['username']);
$password = $_POST['password'];
// Demo credentials; a real system would check a database with password_verify()
if ($username === "admin" && $password === "admin123") {
header("Location: home.php");
exit;
} else {
$error = "Invalid username or password.";
}
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="">
<?php if ($error) echo "<p style='color:red'>$error</p>"; ?>
Username: <input type="text" name="username"
value="<?php echo htmlspecialchars($username); ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="login" value="Login">
<input type="submit" name="cancel" value="Cancel">
</form>
</body>
</html>
Explanation. Both buttons submit the same form, and the button's name tells the script which was pressed. On Login, the credentials are checked and header("Location: home.php") redirects on success. On Cancel, the username is reset to an empty string, so the form is shown blank. The password field is never refilled. exit after header() stops further output.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
How can you query a database in PHP?
Answer
PHP queries a database through the MySQLi extension or PDO. The steps are: connect, run a query, fetch the results, close the connection.
<?php
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT id, name FROM students");
while ($row = $result->fetch_assoc()) {
echo $row['id'] . " - " . $row['name'] . "<br>";
}
$conn->close();
?>
query()sends a SQL statement. For a SELECT it returns a result set.fetch_assoc()returns one row at a time as an associative array.- When the SQL contains user input, use a prepared statement (
prepare(),bind_param(),execute()) to prevent SQL injection.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
How can you retrieve the form data? Illustrate with example.
Answer
Form data is retrieved through the superglobal arrays $_GET, $_POST and $_REQUEST, indexed by the field's name attribute.
$_GETholds data sent in the URL query string (method="get"). It is visible and suitable for searches.$_POSTholds data sent in the request body (method="post"). It is not visible in the URL and is used for logins and large data.$_REQUESTholds both, and also cookies.
<!-- form.html -->
<form action="show.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Send">
</form>
<?php
// show.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
echo "Name: $name<br>Email: $email";
}
?>
htmlspecialchars() escapes the input, which prevents XSS.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is error handler? Write a PHP program to show use of error handler to format and print errors.
Answer
An error handler is a user-defined function that PHP calls instead of its built-in error reporting whenever an error occurs. It is registered with set_error_handler(). The handler receives the error number, message, file and line, so the program can format and print errors in its own way.
<?php
function myHandler($errno, $errstr, $errfile, $errline) {
echo "<b>Error [$errno]:</b> $errstr<br>";
echo "File: $errfile, Line: $errline<br>";
}
set_error_handler("myHandler");
echo $undefinedVar; // triggers a warning -> handled by myHandler
echo 10 / 0; // DivisionByZeroError is an exception, not handled here
?>
For the first statement the output is similar to:
Error [2]: Undefined variable $undefinedVar
File: /var/www/test.php, Line: 9
The handler can also be called deliberately with trigger_error("Custom message", E_USER_WARNING).
Note that division by zero in PHP 8 throws DivisionByZeroError, which must be caught with try/catch.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
For the following JSON file named BIT.JSON, write a PHP program to read information from this JSON file:
{Name: "Gunadi", Email: "Gunadi@gmail.com", Dob: "January 1", Age: 30}
{Name: "Gunadi", Email: "Gunadi@gmail.com", Dob: "January 1", Age: 30}
Answer
The given text is not strictly valid JSON, because keys must be double-quoted. The valid file is:
{"Name": "Gunadi", "Email": "Gunadi@gmail.com", "Dob": "January 1", "Age": 30}
PHP reads it with file_get_contents() and decodes it with json_decode().
<?php
$json = file_get_contents("BIT.JSON");
$data = json_decode($json, true); // true -> associative array
if ($data === null) {
die("Invalid JSON file");
}
echo "Name: " . $data['Name'] . "<br>";
echo "Email: " . $data['Email'] . "<br>";
echo "DOB: " . $data['Dob'] . "<br>";
echo "Age: " . $data['Age'] . "<br>";
?>
Output:
Name: Gunadi
Email: Gunadi@gmail.com
DOB: January 1
Age: 30
Without true, json_decode() returns an object, and the fields are read as $data->Name.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
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.
Answer
Comments in PHP
- Single line:
// commentor# comment - Multi-line:
/* comment ... */
<?php
// Program: read name and roll number and print them
/* The values come from an HTML form
submitted with the POST method */
# Get values from the form
if (isset($_POST['submit'])) {
$name = $_POST['name']; // student's name
$roll = $_POST['roll']; // roll number
// Print the values
echo "Name: $name<br>";
echo "Roll No: $roll";
}
?>
<form method="post">
Name: <input type="text" name="name"><br>
Roll No: <input type="text" name="roll"><br>
<input type="submit" name="submit" value="Show">
</form>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
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.
Answer
<?php
function concat(string $st1, string $st2): string {
$st3 = $st1 . $st2; // . is the concatenation operator
return $st3;
}
$a = "Web ";
$b = "Technology";
echo concat($a, $b); // Web Technology
?>
The function takes two string arguments, joins them with the . operator and returns the new string $st3.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Write a PHP program to extract subset of a string array using array_slice() function.
Answer
array_slice($array, $offset, $length, $preserve_keys) returns a part of an array without changing the original. A negative offset counts from the end.
<?php
$names = ["Ram", "Sita", "Hari", "Gita", "Shyam"];
$subset = array_slice($names, 1, 3);
print_r($subset);
// Array ( [0] => Sita [1] => Hari [2] => Gita )
$last2 = array_slice($names, -2);
print_r($last2);
// Array ( [0] => Gita [1] => Shyam )
?>
The first call starts at index 1 and takes 3 elements. Numeric keys are renumbered unless the fourth argument is true.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Describe an anonymous class using suitable example.
Answer
An anonymous class is a class with no name, declared with new class { ... } (PHP 7+). It is created and instantiated in one step. It is useful for a simple one-off object, such as a mock or a quick implementation of an interface.
<?php
interface Greeter {
public function greet($name);
}
$obj = new class("Welcome") implements Greeter {
private $msg;
public function __construct($m) { $this->msg = $m; }
public function greet($name) {
return $this->msg . ", " . $name . "!";
}
};
echo $obj->greet("Ram"); // Welcome, Ram!
?>
The class can have properties, methods and a constructor, and it can extend a class or implement interfaces. Internally PHP gives it a generated name, so it cannot be instantiated a second time by name.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Write a PHP program for illustrating the starting and ending of session.
Answer
A session is started with session_start() and ended with session_unset() and session_destroy().
<?php
// page1.php - start the session
session_start();
$_SESSION['user'] = "Ram";
echo "Session started. User = " . $_SESSION['user'];
echo "<br><a href='page2.php'>Go to page 2</a>";
?>
<?php
// page2.php - use, then end the session
session_start();
echo "Hello " . $_SESSION['user'] . "<br>";
session_unset(); // remove all session variables
session_destroy(); // destroy the session data on the server
echo "Session ended.";
?>
session_start() must be called before any output. It creates a session ID, normally stored in a cookie named PHPSESSID, and loads the data in $_SESSION.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
How can you embed PHP code in web pages? Write a PHP program to illustrate the concepts of continue and break statements.
Answer
Embedding PHP in web pages. PHP code is placed in an HTML page inside tags. The file is saved with the .php extension, and the server runs the PHP and sends plain HTML to the browser.
- Standard tags:
<?php ... ?> - Echo shortcut:
<?= $x ?> - Script style:
<script language="php"> ... </script>(removed in PHP 7) - Short tags
<? ... ?>(only ifshort_open_tagis enabled)
<html>
<body>
<h1>Today is <?php echo date("l"); ?></h1>
</body>
</html>
break and continue
breakends the loop (or switch) immediately.continueskips the rest of the current iteration and goes to the next one.
<?php
echo "Using continue (skip 3):<br>";
for ($i = 1; $i <= 6; $i++) {
if ($i == 3) continue;
echo $i . " "; // 1 2 4 5 6
}
echo "<br>Using break (stop at 4):<br>";
for ($i = 1; $i <= 6; $i++) {
if ($i == 4) break;
echo $i . " "; // 1 2 3
}
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
Describe variables and missing parameters with examples. Write a PHP program to implement functions containing parameters by reference.
Answer
Variables. A variable stores data and begins with $. Its type is decided by the assigned value ($x = 5;, then $x = "five"; is allowed). A variable has a scope: local, global, static or a function parameter.
Missing parameters. If a function is called with fewer arguments than it declares, PHP 7 raised a warning, and PHP 8 throws an ArgumentCountError. To make a parameter optional, give it a default value. Default parameters must come after the required ones.
<?php
function greet($name, $greeting = "Hello") {
return "$greeting, $name!";
}
echo greet("Sita"); // Hello, Sita!
echo greet("Sita", "Namaste"); // Namaste, Sita!
// greet(); -> ArgumentCountError (required $name is missing)
?>
Parameters by reference. Normally a function receives a copy of the argument. A & before the parameter passes the variable itself, so changes inside the function affect the caller's variable.
<?php
function addBonus(&$salary, $bonus) {
$salary = $salary + $bonus;
}
function swap(&$a, &$b) {
$t = $a; $a = $b; $b = $t;
}
$s = 20000;
addBonus($s, 5000);
echo $s; // 25000
$x = 1; $y = 2;
swap($x, $y);
echo " $x $y"; // 2 1
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
How can you create a database connection? Create a PHP form that includes text field, password field, radio button elements. Now write a function to insert the data in the fields into a database table.
Answer
Creating a database connection. With MySQLi, a connection is made by new mysqli(host, user, password, database). The connection must be checked for errors.
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(255),
gender VARCHAR(10)
);
Form and insert function
<?php
function insertUser($conn, $username, $password, $gender) {
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, password, gender) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $hash, $gender);
$ok = $stmt->execute();
$stmt->close();
return $ok;
}
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (insertUser($conn, $_POST['username'], $_POST['password'], $_POST['gender'])) {
echo "Record inserted successfully.";
} else {
echo "Insert failed.";
}
}
?>
<form method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br>
<input type="submit" value="Save">
</form>
The prepared statement prevents SQL injection, and the password is stored hashed, never as plain text.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
How is the approximate equality of two strings done in PHP? Write a program to demonstrate it.
Answer
Two strings are approximately equal when they are not identical but sound alike or differ by only a few characters. PHP provides these functions:
soundex($s)returns a 4-character code based on pronunciation.metaphone($s)returns a phonetic key, and is more accurate than soundex.levenshtein($a, $b)returns the minimum number of insertions, deletions and substitutions needed to turn one string into the other.similar_text($a, $b, $percent)returns the number of matching characters and the similarity percentage.
<?php
$a = "Smith";
$b = "Smyth";
if (soundex($a) == soundex($b)) {
echo "Sound alike (" . soundex($a) . ")<br>"; // S530
}
echo "Metaphone: " . metaphone($a) . " / " . metaphone($b) . "<br>";
echo "Levenshtein distance: " . levenshtein($a, $b) . "<br>"; // 1
similar_text($a, $b, $pct);
echo "Similarity: " . round($pct, 1) . "%"; // 80%
?>
"Smith" and "Smyth" differ by one letter, so the Levenshtein distance is 1. Both have the soundex code S530.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is a cookie? Write PHP program to create cookie.
Answer
A cookie is a small piece of data that the server asks the browser to store. The browser sends it back with every later request to that site. Cookies are used to remember users, preferences and login state.
A cookie is created with setcookie(name, value, expire, path, domain, secure, httponly). It must be called before any output is sent, because it is part of the HTTP headers.
<?php
// Create a cookie that lasts 7 days
setcookie("username", "Ram", time() + (7 * 24 * 60 * 60), "/");
?>
<html><body>
<?php
if (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'];
} else {
echo "Cookie set. Reload the page to read it.";
}
?>
</body></html>
The value is read through $_COOKIE['username'], and it is available only on the next request. To delete the cookie, set its expiry time in the past: setcookie("username", "", time() - 3600);.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Define error reporting and error suppression with examples.
Answer
Error reporting. Error reporting controls which PHP errors are reported. It is set with error_reporting() or in php.ini, and display_errors decides whether they are shown on the page.
<?php
error_reporting(E_ALL); // report all errors
ini_set('display_errors', 1); // show them on screen
echo $x; // Warning: Undefined variable $x
error_reporting(0); // report nothing
?>
Common levels are E_ERROR, E_WARNING, E_NOTICE and E_ALL. Levels can be combined, for example E_ALL & ~E_NOTICE.
Error suppression. The @ operator placed before an expression hides any error message that expression would produce. The error still happens, but it is not displayed.
<?php
$file = @fopen("missing.txt", "r"); // no warning is displayed
if (!$file) {
echo "Could not open the file.";
}
?>
Suppression hides problems, so it should be used rarely. Checking the return value, as above, is the proper way to handle the failure.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a PHP program to write on a file.
Answer
A file is written with fopen() in write mode and fwrite(), or in one step with file_put_contents().
<?php
$file = fopen("data.txt", "w"); // "w" truncates, "a" appends
if ($file) {
fwrite($file, "Hello, Nepal!\n");
fwrite($file, "Web Technology II\n");
fclose($file);
echo "File written successfully.";
} else {
echo "Cannot open file.";
}
// shorter way, appending to the file
file_put_contents("data.txt", "Another line\n", FILE_APPEND);
?>
Mode w creates the file if it does not exist and erases the old content. Mode a adds to the end. The file must be closed with fclose().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a PHP program to illustrate the use of exception handling.
Answer
An exception is an object thrown when an error occurs. The code that may fail is placed in a try block, throw raises the exception, catch handles it, and finally always runs.
<?php
function divide($a, $b) {
if ($b == 0) {
throw new Exception("Division by zero is not allowed");
}
return $a / $b;
}
try {
echo divide(10, 2) . "<br>"; // 5
echo divide(5, 0); // throws
} catch (Exception $e) {
echo "Caught: " . $e->getMessage();
} finally {
echo "<br>Done.";
}
?>
Output:
5
Caught: Division by zero is not allowed
Done.
A custom exception can be made by extending the Exception class.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Differentiate anonymous function from variable function.
Answer
| Basis | Anonymous function | Variable function |
|---|---|---|
| Meaning | A function without a name, created as a closure object | An ordinary named function called through a variable holding its name |
| Definition | function(...) { ... } assigned to a variable or passed as an argument | The function is defined normally with a name |
| Variable contains | A Closure object | A string, the function's name |
| Scope | Can capture outer variables with use | Behaves like any named function |
| Use | Callbacks (array_map, usort) | Choosing which function to call at run time |
<?php
// anonymous function
$square = function($n) { return $n * $n; };
echo $square(4); // 16
// variable function
function hello($n) { return "Hello $n"; }
$f = "hello";
echo $f("Ram"); // Hello Ram
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a PHP program to access properties and methods of a class.
Answer
Properties and methods of an object are accessed with the object operator ->. Static members are accessed with ::.
<?php
class Student {
public $name;
public $roll;
public static $college = "TU";
public function __construct($name, $roll) {
$this->name = $name;
$this->roll = $roll;
}
public function display() {
echo "Name: $this->name, Roll: $this->roll<br>";
}
public static function hello() {
echo "Welcome to " . self::$college . "<br>";
}
}
$s = new Student("Sita", 12);
echo $s->name . "<br>"; // access a property
$s->roll = 15; // modify a property
$s->display(); // call a method
Student::hello(); // static method
echo Student::$college; // static property
?>
Output: Sita, Name: Sita, Roll: 15, Welcome to TU, TU.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
How can you remove and insert elements in an array? Explain by writing a PHP program using array_splice() for inserting and removing elements in an array.
Answer
Elements are removed with array_pop() (last), array_shift() (first) and unset(). Elements are inserted with array_push(), array_unshift() or $a[] = x. array_splice() can do both at any position.
array_splice(&$array, $offset, $length, $replacement) removes $length elements from $offset and puts the replacement in their place. It changes the original array.
<?php
$a = ["Ram", "Sita", "Hari", "Gita"];
// Remove 1 element at index 1 (Sita)
array_splice($a, 1, 1);
print_r($a); // Ram, Hari, Gita
// Insert without removing anything (length 0)
array_splice($a, 1, 0, ["Binod", "Anil"]);
print_r($a); // Ram, Binod, Anil, Hari, Gita
// Replace 2 elements from index 3
array_splice($a, 3, 2, "Maya");
print_r($a); // Ram, Binod, Anil, Maya
?>
The array is renumbered after each call.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a PHP program to demonstrate the concept of inheritance.
Answer
Inheritance lets a child class reuse the properties and methods of a parent class. It is declared with extends. The child can add members and override parent methods, and parent:: calls the parent version.
<?php
class Person {
protected $name;
public function __construct($name) { $this->name = $name; }
public function show() { echo "Name: $this->name<br>"; }
}
class Student extends Person {
private $roll;
public function __construct($name, $roll) {
parent::__construct($name); // call parent constructor
$this->roll = $roll;
}
public function show() { // overriding
parent::show();
echo "Roll: $this->roll<br>";
}
}
$s = new Student("Sita", 7);
$s->show();
?>
Output:
Name: Sita
Roll: 7
PHP supports single inheritance only. A final class cannot be extended.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
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.
Answer
Server side scripting. Server side scripting means that the script runs on the web server, and only its output (usually HTML) is sent to the browser. The user never sees the source code. It is used to generate dynamic pages, process forms, access databases and manage sessions. Examples are PHP, ASP.NET, JSP and Node.js.
Defining and declaring variables. A PHP variable begins with $, then a letter or underscore, then letters, digits or underscores. Names are case-sensitive. There is no separate declaration. A variable is created when a value is first assigned and takes its type from the value.
$name = "Ram"; // string
$age = 20; // int
$pi = 3.14; // float
$ok = true; // bool
while loop (condition tested first)
<?php
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
?>
Output: 1 2 3 4 5
do while loop (body runs at least once, the condition is tested afterwards)
<?php
$i = 1;
do {
echo $i * 2 . " ";
$i++;
} while ($i <= 5);
?>
Output: 2 4 6 8 10
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
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.
Answer
Defining and declaring functions. A function is a named block of code that is run when it is called. It is defined with the function keyword. It may take parameters (with optional defaults) and return a value.
function add($a, $b = 0) {
return $a + $b;
}
echo add(3, 4); // 7
Global versus static variable
| Global variable | Static variable |
|---|---|
| Declared outside all functions | Declared inside a function with static |
Not visible inside functions unless global or $GLOBALS is used | Visible only inside that function |
| Exists for the whole script | Keeps its value between calls of the function |
| Can be changed by any code | Can be changed only inside its function |
Program
<?php
$total = 100; // global
function addToTotal($n) {
global $total; // access the global variable
$total += $n;
}
function visits() {
static $count = 0; // keeps its value
$count++;
echo "Visit $count<br>";
}
addToTotal(50);
echo "Total: $total<br>"; // Total: 150
visits(); // Visit 1
visits(); // Visit 2
visits(); // Visit 3
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
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.
Answer
PHP Data Objects (PDO). PDO is a database abstraction layer in PHP. It provides one common interface for many databases (MySQL, PostgreSQL, SQLite and others), so changing the database mostly needs only a new connection string. It supports prepared statements and exceptions.
$pdo = new PDO("mysql:host=localhost;dbname=college", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
MySQLi object interface. MySQLi (MySQL Improved) works only with MySQL, and offers an object-oriented and a procedural style. In the object interface:
new mysqli(host, user, pass, db)creates the connection object, andconnect_errorreports failure.$conn->query($sql)runs a statement and returns amysqli_resultobject.prepare()andbind_param()give prepared statements.- Methods of the result object, such as
fetch_assoc(),fetch_row()andfetch_array(), read rows.num_rowsgives the number of rows. $conn->close()closes the connection.
Program: read and display data
<?php
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT id, name, email FROM students");
?>
<table border="1">
<tr><th>ID</th><th>Name</th><th>Email</th></tr>
<?php if ($result->num_rows > 0): ?>
<?php while ($row = $result->fetch_assoc()): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo htmlspecialchars($row['name']); ?></td>
<td><?php echo htmlspecialchars($row['email']); ?></td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr><td colspan="3">No records found</td></tr>
<?php endif; ?>
</table>
<?php $conn->close(); ?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How is class different from interface? Illustrate with an example.
Answer
| Class | Interface |
|---|---|
Declared with class | Declared with interface |
| Can have properties and implemented methods | Only method signatures (and constants), no implementation and no properties |
Instantiated with new | Cannot be instantiated |
| A class extends only one class | A class can implement many interfaces |
| Describes what an object is and does | Describes a contract that implementing classes must follow |
<?php
interface Shape {
public function area(); // no body
}
class Circle implements Shape {
private $r;
public function __construct($r) { $this->r = $r; }
public function area() { return M_PI * $this->r ** 2; }
}
class Rectangle implements Shape {
public function __construct(private $w, private $h) {}
public function area() { return $this->w * $this->h; }
}
$c = new Circle(2);
echo round($c->area(), 2); // 12.57
$r = new Rectangle(3, 4);
echo " " . $r->area(); // 12
?>
Both classes must implement area(). If they do not, PHP gives a fatal error.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What is a session? How can you handle sessions in PHP?
Answer
A session stores information about a user on the server across several page requests. HTTP is stateless, so a session lets the server remember a user, for example after login. Each visitor gets a unique session ID, normally kept in a cookie (PHPSESSID), while the data stays on the server in $_SESSION.
Handling sessions in PHP
- Call
session_start()at the top of every page, before any output. - Store data:
$_SESSION['user'] = "Ram"; - Read data on any page:
echo $_SESSION['user']; - Remove one value with
unset($_SESSION['user']). - End the session with
session_unset()andsession_destroy().
<?php
session_start();
if (!isset($_SESSION['visits'])) {
$_SESSION['visits'] = 0;
}
$_SESSION['visits']++;
echo "You have visited " . $_SESSION['visits'] . " time(s).";
?>
session_regenerate_id(true) after login helps prevent session fixation.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Define error handlers and error logs with examples.
Answer
Error handler. A user-defined function registered with set_error_handler(). PHP calls it when an error occurs, so the program decides how the error is shown or handled.
<?php
function handler($errno, $errstr, $errfile, $errline) {
echo "Error [$errno]: $errstr in $errfile on line $errline<br>";
}
set_error_handler("handler");
echo $missing; // goes to handler()
?>
Error log. An error log is a file in which errors are recorded, so they can be reviewed later without being shown to users. It is configured in php.ini (log_errors = On, error_log = /path/php_errors.log) or written with error_log().
<?php
ini_set('log_errors', 1);
ini_set('error_log', 'errors.log');
ini_set('display_errors', 0);
error_log("Database connection failed", 3, "errors.log"); // type 3: append to file
?>
Together, a handler can format the error and call error_log(), so users see a friendly message and developers get the details in the log.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write a PHP program to read a file.
Answer
<?php
$filename = "data.txt";
if (file_exists($filename)) {
// Method 1: read the whole file
echo file_get_contents($filename);
echo "<hr>";
// Method 2: read line by line
$f = fopen($filename, "r");
while (($line = fgets($f)) !== false) {
echo htmlspecialchars($line) . "<br>";
}
fclose($f);
} else {
echo "File not found.";
}
?>
fopen() with mode r opens the file for reading. fgets() reads one line, fread($f, filesize($filename)) reads a given number of bytes, and feof() tests for the end of the file. fclose() releases the file.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe the concepts of display_errors, variables_order and request_order in PHP.ini Settings.
Answer
php.ini is PHP's main configuration file.
display_errors. It decides whether errors are shown in the browser output. display_errors = On suits development. Off is used on a live site, so internal details are not exposed. Errors can still be written to a log with log_errors.
variables_order. It sets which superglobal arrays (Environment, Get, Post, Cookie, Server) PHP fills and in what order. The default is "EGPCS". Letters that are left out are not created, so "GPCS" would leave $_ENV empty. Later letters override earlier ones with the same name.
request_order. It sets the order in which GET, POST and COOKIE data are merged into $_REQUEST. A typical value is "GP". Later sources override earlier ones, so with GP a POST value overrides a GET value of the same name. If it is empty, the value of variables_order is used. Cookies are included only if C is listed.
display_errors = Off
variables_order = "GPCS"
request_order = "GP"
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe the date time functions with examples.
Answer
PHP has many functions for date and time. They use the Unix timestamp, the number of seconds since 1 January 1970.
| Function | Purpose |
|---|---|
time() | Current timestamp |
date(format, ts) | Formats a timestamp |
mktime(h,i,s,m,d,y) | Makes a timestamp |
strtotime(str) | Converts an English date string to a timestamp |
checkdate(m,d,y) | Validates a date |
date_default_timezone_set() | Sets the time zone |
getdate() | Returns date parts as an array |
<?php
date_default_timezone_set("Asia/Kathmandu");
echo date("Y-m-d H:i:s") . "<br>"; // e.g. 2026-10-21 14:30:00
echo date("l, d F Y") . "<br>"; // Wednesday, 21 October 2026
$ts = mktime(0, 0, 0, 12, 25, 2026);
echo date("d/m/Y", $ts) . "<br>"; // 25/12/2026
echo date("Y-m-d", strtotime("+1 week")) . "<br>";
var_dump(checkdate(2, 30, 2026)); // bool(false)
$d = getdate();
echo $d['year'];
?>
The format characters include Y (year), m (month), d (day), H (hour), i (minute), s (second) and l (day name).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write a PHP program to demonstrate use of constructor.
Answer
A constructor is a special method named __construct(). PHP calls it automatically when an object is created with new. It is used to initialise the properties of the object. A __destruct() method runs when the object is destroyed.
<?php
class Student {
public $name;
public $roll;
public function __construct($name, $roll) {
$this->name = $name;
$this->roll = $roll;
echo "Object created for $name<br>";
}
public function show() {
echo "Name: $this->name, Roll: $this->roll<br>";
}
public function __destruct() {
echo "Object destroyed<br>";
}
}
$s = new Student("Ram", 5); // constructor runs automatically
$s->show();
?>
Output:
Object created for Ram
Name: Ram, Roll: 5
Object destroyed
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How conversion between arrays and variables is done using extract() and compact() functions?
Answer
compact() converts variables into an array, and extract() converts an array into variables.
compact(). It takes variable names as strings. It returns an associative array whose keys are those names and whose values are the variables' values.
extract(). It takes an associative array and creates a variable for each key, holding that element's value. By default, existing variables with the same name are overwritten. This can be controlled with flags such as EXTR_SKIP and EXTR_PREFIX_ALL.
<?php
$name = "Sita";
$age = 22;
$arr = compact('name', 'age');
print_r($arr); // Array ( [name] => Sita [age] => 22 )
$info = ["city" => "Pokhara", "zip" => 33700];
extract($info);
echo "$city $zip"; // Pokhara 33700
?>
extract() should not be used on untrusted input such as $_POST, because it can overwrite important variables.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What is exploding and imploding of strings? Illustrate with an example.
Answer
Exploding splits a string into an array using a delimiter, with explode(delimiter, string, limit). Imploding joins array elements into one string using a glue string, with implode(glue, array) (alias join()).
<?php
$str = "Ram,Sita,Hari,Gita";
$arr = explode(",", $str); // string -> array
print_r($arr);
// Array ( [0] => Ram [1] => Sita [2] => Hari [3] => Gita )
$new = implode(" - ", $arr); // array -> string
echo $new; // Ram - Sita - Hari - Gita
print_r(explode(",", $str, 2)); // limit: [0] => Ram, [1] => Sita,Hari,Gita
?>
They are used, for example, to turn a comma separated list into an array for processing, and to build one from the results.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
Why is PHP a loosely typed language? How is the for loop different from the foreach loop? Write a PHP program to demonstrate the use of both loops.
Answer
Loosely typed language. In PHP a variable has no declared type. Its type is decided by the value it currently holds and can change at run time ($x = 5; $x = "five";). PHP also converts types automatically in expressions, so "5" + 3 gives 8. Because the type is not fixed or checked at declaration, PHP is called loosely (dynamically) typed.
for versus foreach
| for | foreach |
|---|---|
| Used when the number of iterations is known, driven by a counter | Used to go through every element of an array or object |
| Needs initialisation, condition and increment | No counter is required |
Elements accessed by index $a[$i] | Gives each value (and key) directly |
| Works with any condition | Works only on arrays and objects |
Program
<?php
$marks = [70, 85, 90, 65];
echo "for loop:<br>";
for ($i = 0; $i < count($marks); $i++) {
echo "Marks[$i] = " . $marks[$i] . "<br>";
}
echo "foreach loop:<br>";
foreach ($marks as $index => $m) {
echo "Marks[$index] = $m<br>";
}
$student = ["name" => "Ram", "age" => 20];
foreach ($student as $key => $value) {
echo "$key : $value<br>";
}
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
How are indexed arrays different from associative arrays? Write a PHP program to demonstrate the conversion between array and variables.
Answer
Indexed versus associative arrays
| Indexed array | Associative array |
|---|---|
| Keys are integers, starting at 0 by default | Keys are named strings (or chosen numbers) |
$a = ["Ram", "Sita"]; | $a = ["name" => "Ram", "age" => 20]; |
Accessed as $a[0] | Accessed as $a['name'] |
| Suited to ordered lists | Suited to labelled records |
Conversion between arrays and variables. extract() turns array elements into variables, and compact() turns variables into an array.
<?php
// Indexed and associative arrays
$colors = ["Red", "Green", "Blue"];
echo $colors[1]; // Green
$student = ["name" => "Sita", "age" => 21, "city" => "Pokhara"];
echo $student['city']; // Pokhara
// array -> variables
extract($student);
echo "<br>$name is $age years old from $city.";
// Sita is 21 years old from Pokhara.
// variables -> array
$title = "PHP";
$price = 500;
$book = compact('title', 'price');
print_r($book); // Array ( [title] => PHP [price] => 500 )
?>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
What are the response headers? Create a PHP login form that contains username, password and a login type field defined by dropdown menu. The login type options can be normal or admin. Now, write a function for implementing the login event. The event should be redirected to admin.php if the login credentials match and if the login type is admin otherwise it should be redirected to hello.php. Create a proper database connection based on your own assumption.
Answer
Response headers. Response headers are the name: value lines sent by the server before the body of an HTTP response. They describe the response, for example Content-Type, Content-Length, Set-Cookie, Location (redirect), Cache-Control and Expires. In PHP, header() sets them, and it must be called before any output.
header("Content-Type: text/html; charset=UTF-8");
header("Location: admin.php"); // redirect
Database (assumed)
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE,
password VARCHAR(255), -- stored with password_hash()
role VARCHAR(10) -- 'normal' or 'admin'
);
login.php
<?php
function loginUser($conn, $username, $password, $type) {
$stmt = $conn->prepare("SELECT password, role FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($hash, $role);
if ($stmt->fetch() && password_verify($password, $hash) && $role === $type) {
session_start();
$_SESSION['user'] = $username;
$_SESSION['role'] = $role;
$stmt->close();
if ($type === "admin") {
header("Location: admin.php");
} else {
header("Location: hello.php");
}
exit;
}
$stmt->close();
return false;
}
$conn = new mysqli("localhost", "root", "", "college");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
$error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!loginUser($conn, trim($_POST['username']), $_POST['password'], $_POST['type'])) {
$error = "Invalid credentials or login type.";
}
}
?>
<form method="post">
<?php if ($error) echo "<p style='color:red'>$error</p>"; ?>
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
Login type:
<select name="type">
<option value="normal">Normal</option>
<option value="admin">Admin</option>
</select><br>
<input type="submit" value="Login">
</form>
If the credentials match and the chosen type is admin, the user is redirected to admin.php. For the normal type, the user is redirected to hello.php. In both cases the stored role must equal the chosen type, so a normal user cannot log in as admin.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a program that will read your name as input string. Access and display the individual characters in the name string.
Answer
A string can be treated as an array of characters, so each character is read by its index, starting at 0. strlen() gives the length.
<?php
$name = "Gunadi"; // or $_POST['name'] from a form
echo "Name: $name<br>";
for ($i = 0; $i < strlen($name); $i++) {
echo "Character at index $i : " . $name[$i] . "<br>";
}
?>
Output:
Character at index 0 : G
Character at index 1 : u
Character at index 2 : n
Character at index 3 : a
Character at index 4 : d
Character at index 5 : i
Reading the name from the keyboard in a form:
<form method="post">
Name: <input type="text" name="name">
<input type="submit" value="Show">
</form>
str_split($name) gives the same characters as an array, which foreach can loop over. For non-ASCII text, use mb_str_split().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
How can you handle cookies and sessions? Illustrate with examples.
Answer
Cookies are small pieces of data stored in the user's browser by the server and sent back with every later request to the same site. Sessions store user data on the server, and only a session ID (usually kept in a cookie) is held by the browser. Sessions are therefore more secure for sensitive data.
(a) Handling cookies in PHP
<?php
// set a cookie (must be called before any output)
setcookie("username", "Ram", time() + 3600, "/"); // expires in 1 hour
// read a cookie
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
} else {
echo "Hello, guest";
}
// delete a cookie (set expiry in the past)
setcookie("username", "", time() - 3600, "/");
?>
(b) Handling sessions in PHP
login.php
<?php
session_start(); // start or resume a session
$_SESSION["user"] = "Ram"; // store data on the server
$_SESSION["role"] = "student";
echo "Logged in";
?>
profile.php
<?php
session_start();
if (isset($_SESSION["user"])) {
echo "Hello " . $_SESSION["user"];
} else {
header("Location: login.php");
exit;
}
?>
logout.php
<?php
session_start();
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?>
Difference: cookies live on the client, can be edited by the user, and hold small data (about 4 KB); sessions live on the server, end when the browser closes or the session is destroyed, and are suited to login information.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What is anonymous class? Write a program to demonstrate the use of anonymous classes.
Answer
An anonymous class is a class without a name, declared and instantiated in a single expression using new class { ... } (PHP 7+). It is useful for a one-off object, for example a simple implementation of an interface or a quick mock in tests, where a separate named class is not worth writing. It can take constructor arguments, extend a class and implement interfaces.
<?php
interface Logger {
public function log($msg);
}
class App {
public function __construct(private Logger $logger) {}
public function run() { $this->logger->log("Application started"); }
}
// anonymous class implementing Logger, with a constructor argument
$logger = new class("LOG") implements Logger {
private $prefix;
public function __construct($prefix) { $this->prefix = $prefix; }
public function log($msg) { echo "[{$this->prefix}] $msg\n"; }
};
$app = new App($logger);
$app->run();
// simple anonymous object
$obj = new class {
public $name = "Sita";
public function greet() { return "Hello, " . $this->name; }
};
echo $obj->greet();
?>
Output:
[LOG] Application started
Hello, Sita
Each anonymous class has a generated internal name, so two identical declarations in different places produce different classes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What is HTTP authentication? How is it done?
Answer
HTTP authentication is a mechanism by which a web server asks a client for credentials (username and password) before it allows access to a protected resource. The server replies with status 401 Unauthorized and a WWW-Authenticate header; the browser shows a login dialog and resends the request with an Authorization header.
Main types
- Basic authentication: username and password are joined as
user:pass, Base64 encoded and sent in theAuthorizationheader. It is simple but not encrypted, so it must be used over HTTPS. - Digest authentication: a hash of the credentials with a server nonce is sent, so the password is not sent in plain form.
How it is done (flow)
- Client requests a protected page.
- Server sends
401withWWW-Authenticate: Basic realm="Restricted". - Browser prompts the user and resends the request with
Authorization: Basic <base64>. - Server validates the credentials and returns the page, or
401again.
Example in PHP
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="Admin Area"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authentication required';
exit;
}
if ($_SERVER['PHP_AUTH_USER'] == 'admin' && $_SERVER['PHP_AUTH_PW'] == 'secret') {
echo "Welcome, admin";
} else {
header('HTTP/1.0 401 Unauthorized');
echo 'Invalid credentials';
}
?>
The credentials are available in $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']. In practice, passwords should be stored hashed (password_hash, password_verify).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What is the error handler? Write a program to demonstrate error handler function.
Answer
An error handler is a user-defined function that PHP calls when a runtime error (warning, notice, etc.) occurs, instead of the built-in handler. It is registered with set_error_handler(). It lets the programmer log errors, show friendly messages or send alerts. The function receives the error number, message, file and line.
<?php
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "<b>Error [$errno]:</b> $errstr<br>";
echo "In file $errfile on line $errline<br>";
error_log("Error: $errstr in $errfile:$errline"); // write to log
return true; // prevent PHP's default handler
}
set_error_handler("myErrorHandler");
echo $undefinedVar; // triggers a notice/warning
$result = 10 / 0; // DivisionByZeroError is an exception in PHP 8
?>
Using trigger_error() with a custom error:
<?php
function check($age) {
if ($age < 18) trigger_error("Age must be at least 18", E_USER_WARNING);
}
set_error_handler(function($no, $str) { echo "Custom handler: $str"; });
check(15);
?>
Output: Custom handler: Age must be at least 18.
Note that set_error_handler() cannot catch fatal errors; use try/catch for exceptions, and restore_error_handler() to go back to the default.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a program to parse a CSV file and display the content in the file.
Answer
PHP can read a CSV file with fopen() and fgetcsv(), which splits each line into an array of fields.
Assume students.csv:
Name,Roll,Marks
Ram,1,85
Sita,2,92
Hari,3,78
<?php
$file = "students.csv";
if (($handle = fopen($file, "r")) !== false) {
echo "<table border='1'>";
$first = true;
while (($row = fgetcsv($handle, 1000, ",")) !== false) {
echo "<tr>";
foreach ($row as $cell) {
echo $first ? "<th>" . htmlspecialchars($cell) . "</th>"
: "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>";
$first = false;
}
echo "</table>";
fclose($handle);
} else {
echo "Unable to open file.";
}
?>
fgetcsv() returns an array for each line and false at end of file. The first row is shown as the table header. htmlspecialchars() prevents HTML injection from file content.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Consider you have student records in a database table. Now create a PHP page with delete button action and a text field. The button should delete a record if it matches the name of the student entered in the text field. Use your own assumption for the database table.
Answer
Assumed table
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
roll INT,
marks INT
);
delete_student.php
<?php
$conn = new mysqli("localhost", "root", "", "school");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
$msg = "";
if (isset($_POST['delete'])) {
$name = trim($_POST['name']);
$stmt = $conn->prepare("DELETE FROM students WHERE name = ?");
$stmt->bind_param("s", $name);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$msg = "Record of $name deleted.";
} else {
$msg = "No student named $name found.";
}
$stmt->close();
}
?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="">
<label>Student name:</label>
<input type="text" name="name" required>
<button type="submit" name="delete">Delete</button>
</form>
<p><?= htmlspecialchars($msg) ?></p>
</body>
</html>
The page shows a text field and a Delete button. On submit, a prepared statement deletes the row whose name equals the entered text (this protects against SQL injection), and a message tells whether any record was deleted.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Differentiate GET method from POST method with examples.
Answer
| Basis | GET | POST |
|---|---|---|
| Data location | Appended to the URL as a query string | Sent in the HTTP request body |
| Visibility | Visible in the address bar, history and logs | Not shown in the URL |
| Security | Less secure; not for passwords | More secure (still needs HTTPS) |
| Data size | Limited (about 2000 characters) | No practical limit |
| Caching/bookmark | Can be cached and bookmarked | Not cached or bookmarked |
| Use | Fetching or searching data (idempotent) | Submitting forms, changing data, uploads |
| PHP array | $_GET | $_POST |
| Data type | Only ASCII text | Text and binary (file upload) |
GET example
<form method="get" action="search.php">
<input type="text" name="q"> <input type="submit">
</form>
URL becomes search.php?q=nepal.
<?php echo "You searched: " . htmlspecialchars($_GET['q']); ?>
POST example
<form method="post" action="login.php">
<input type="text" name="user">
<input type="password" name="pass">
<input type="submit">
</form>
<?php
$user = $_POST['user'];
echo "Welcome " . htmlspecialchars($user);
?>
The credentials do not appear in the URL.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
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.
Answer
<?php
class Employee {
public $name;
public $id;
protected $salary;
public function __construct($name, $id, $salary) {
$this->name = $name;
$this->id = $id;
$this->salary = $salary;
}
public function getAnnualSalary() {
return $this->salary * 12;
}
public function display() {
echo "ID: {$this->id}<br>";
echo "Name: {$this->name}<br>";
echo "Monthly salary: Rs " . $this->salary . "<br>";
echo "Annual salary: Rs " . $this->getAnnualSalary() . "<br>";
}
}
$emp = new Employee("Ram Sharma", 101, 40000);
$emp->display();
?>
Output:
ID: 101
Name: Ram Sharma
Monthly salary: Rs 40000
Annual salary: Rs 480000
The class has attributes (name, id, salary), a constructor that initialises them, and methods getAnnualSalary() and display(). The object $emp is created with new and its method is called with ->.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BIT 2079 Fifth Semester Web Technology II (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Fifth Semester Web Technology II (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Fifth Semester Web Technology II (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Fifth Semester Web Technology II (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2079 Fifth Semester Software Engineering (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Fifth Semester Software Engineering (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Fifth Semester Software Engineering (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Fifth Semester Software Engineering (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2079 Fifth Semester Information Security (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Fifth Semester Information Security (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Fifth Semester Information Security (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Fifth Semester Information Security (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2079 Fifth Semester Computer Graphics (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Fifth Semester Computer Graphics (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Fifth Semester Computer Graphics (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Fifth Semester Computer Graphics (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2079 Fifth Semester Technical Writing (TU IOST semester board exam, 2079 (BS), via StudyNp) and TU BIT 2082 Fifth Semester Technical Writing (TU IOST semester board exam, 2082 (BS), via StudyNp). Answers are written for this site; check them against your class notes.