Browse papers
A

Section A

Attempt any two questions. (2 × 10 = 20)

3 questions·10 marks each
1long10 marks

What is a function? How can you define and call a function in PHP? Write a PHP program to implement a function with parameters and return value. [4+6]

What is a function?

A function is a named, reusable block of code that performs a specific task. It is defined once and can be called (invoked) many times, which avoids code duplication, improves readability and makes programs modular and easier to maintain. A function may accept input values (parameters/arguments) and may return a result to the caller.

Defining a function in PHP

A user-defined function is declared with the function keyword, followed by the function name, a parenthesised list of parameters and a body enclosed in braces:

function functionName($param1, $param2) {
    // statements
    return $value; // optional
}

Rules:

  • The name must start with a letter or underscore (function names are case-insensitive in PHP).
  • Parameters may have default values, e.g. function greet($name = "Guest").
  • The return statement sends a value back to the caller and ends the function.

Calling a function

A function is called by writing its name followed by parentheses containing the arguments:

$result = functionName($a, $b);

PHP program: function with parameters and a return value

<?php
// Function definition with two parameters and a return value
function add($a, $b) {
    $sum = $a + $b;
    return $sum;        // returns the result to the caller
}

// Calling the function
$x = 15;
$y = 25;
$total = add($x, $y);   // pass arguments, capture return value

echo "The sum of $x and $y is: $total";
// Output: The sum of 15 and 25 is: 40
?>

Here add() takes two parameters $a and $b, computes their sum and returns it; the calling code stores the returned value in $total and prints it.

phpfunctions
2long10 marks

How can you retrieve form data? Write a PHP program to create a form that will take a Fahrenheit value as input and displays the equivalent Celsius value on submit. The conversion is Celsius=(5/9)×(Fahrenheit32)Celsius = (5/9) \times (Fahrenheit - 32). [4+6]

Retrieving form data in PHP

When an HTML form is submitted, PHP makes the submitted values available through the superglobal arrays:

  • $_GET - holds data sent with method="get" (appended to the URL).
  • $_POST - holds data sent with method="post" (sent in the request body, suitable for larger/sensitive data).
  • $_REQUEST - a combined array of GET, POST and COOKIE data.

Each form control is read by its name attribute, e.g. $_POST['fahrenheit']. It is good practice to check whether the form was submitted (e.g. if ($_SERVER['REQUEST_METHOD'] == 'POST') or isset()) and to validate/sanitise the input before using it.

PHP program: Fahrenheit to Celsius converter

<!DOCTYPE html>
<html>
<body>
<form method="post" action="">
    Enter Fahrenheit: <input type="text" name="fahrenheit">
    <input type="submit" name="submit" value="Convert">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["fahrenheit"])) {
    $f = floatval($_POST["fahrenheit"]);   // retrieve form data
    $c = (5 / 9) * ($f - 32);               // apply conversion formula
    echo "$f Fahrenheit = " . round($c, 2) . " Celsius";
}
?>
</body>
</html>

The form posts the Fahrenheit value to the same page; on submit the script reads $_POST['fahrenheit'], applies C=59(F32)C = \frac{5}{9}(F - 32) and displays the equivalent Celsius value.

phpformstemperature-conversion
3long10 marks

What are casting operators? Differentiate for from foreach statement. Write a PHP program to illustrate use of for and foreach. [2+3+5]

Casting operators

Casting operators are used to explicitly convert (type-cast) a value from one data type to another. In PHP a cast is written by placing the target type in parentheses before the value. Common casting operators are:

  • (int) / (integer) - cast to integer
  • (float) / (double) - cast to floating point
  • (string) - cast to string
  • (bool) / (boolean) - cast to boolean
  • (array) - cast to array
  • (object) - cast to object

Example: $n = (int) "25abc"; // $n becomes 25.

Difference between for and foreach

Basisforforeach
PurposeGeneral-purpose loop driven by a counter/conditionSpecifically designed to iterate over arrays/objects
Syntaxfor(init; condition; update){ }foreach($array as $value){ } or foreach($array as $key => $value){ }
Index accessUses an explicit numeric index/counterAutomatically gives each element (and optional key); no manual index needed
Best used whenNumber of iterations is known or based on a conditionTraversing every element of an array, including associative arrays
RiskCan go out of bounds if counter is mismanagedSafe; iterates exactly over existing elements

PHP program illustrating for and foreach

<?php
// Using for loop to print numbers 1 to 5
echo "Using for loop:\n";
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}

echo "\n\nUsing foreach loop:\n";
// Using foreach loop to iterate over an associative array
$marks = array("Math" => 80, "Science" => 90, "English" => 75);
foreach ($marks as $subject => $score) {
    echo "$subject : $score\n";
}
?>

The for loop uses a counter $i to print 1 to 5, while the foreach loop walks through each key-value pair of the associative array without needing an index.

phpcastingloops
B

Section B

Attempt any eight questions. (8 × 5 = 40)

9 questions·5 marks each
4short5 marks

Write a PHP program to parse a CSV file. [5]

A CSV (Comma-Separated Values) file stores tabular data with one record per line and fields separated by commas. PHP provides the built-in function fgetcsv() which reads a line from a file and splits it into an array of fields.

PHP program to parse a CSV file

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

// Open the CSV file for reading
if (($handle = fopen($filename, "r")) !== false) {
    // Read each row until end of file
    while (($row = fgetcsv($handle, 1000, ",")) !== false) {
        // $row is an array of the fields in this line
        $numFields = count($row);
        for ($i = 0; $i < $numFields; $i++) {
            echo $row[$i] . "\t";
        }
        echo "\n";
    }
    fclose($handle);   // close the file
} else {
    echo "Could not open the file $filename";
}
?>

Explanation:

  • fopen() opens the file in read mode.
  • fgetcsv($handle, length, delimiter) reads one line and returns its fields as an array.
  • The while loop iterates over every record; the inner loop prints each field.
  • fclose() releases the file handle.
phpcsvfile-handling
5short5 marks

Define error handling, error reporting and error suppression. [5]

Error handling is the process of detecting, managing and responding to errors that occur while a program runs, so that the application can fail gracefully instead of crashing. In PHP it is done using techniques such as custom error handler functions (set_error_handler()), and exceptions with try { } catch (Exception $e) { } finally { } blocks, allowing the program to display friendly messages or take corrective action.

Error reporting controls which types of errors PHP detects and displays/logs. It is configured with the error_reporting() function or the error_reporting directive in php.ini. For example:

error_reporting(E_ALL);      // report all errors, warnings and notices
ini_set('display_errors', 1); // show them on screen (development)

Levels include E_ERROR, E_WARNING, E_NOTICE, E_ALL, etc. During development all errors are usually reported; in production, errors are logged to a file rather than shown to users.

Error suppression is the act of preventing PHP from displaying an error for a particular expression. It is done using the error-control operator @ placed before an expression:

$value = @file_get_contents("missing.txt"); // suppresses warning if file is absent

The @ operator silences any error message generated by that expression. It should be used sparingly because it hides problems and can make debugging difficult.

phperror-handling
6short5 marks

What is a session? Write a PHP program for maintaining user data with sessions. [5]

Session

A session is a server-side mechanism for storing user-specific data across multiple pages during a single visit (since HTTP is stateless). When a session starts, PHP creates a unique session ID, stores it in a cookie on the client (PHPSESSID), and keeps the associated data in the $_SESSION superglobal array on the server. Sessions are commonly used for login state, shopping carts and user preferences.

PHP program: maintaining user data with sessions

<?php
session_start();   // must be the first thing on every page using sessions

// Store user data in the session
$_SESSION["username"] = "Ram";
$_SESSION["role"] = "admin";

// Retrieve and use the session data
if (isset($_SESSION["username"])) {
    echo "Welcome, " . $_SESSION["username"];
    echo "<br>Your role is: " . $_SESSION["role"];
}

// To remove data / end the session:
// unset($_SESSION["username"]);
// session_destroy();
?>

Explanation:

  • session_start() begins (or resumes) a session and must be called before any output.
  • Data is saved in $_SESSION and remains available on subsequent pages that also call session_start().
  • unset() removes a single value and session_destroy() ends the whole session (e.g. on logout).
phpsessionsstate-management
7short5 marks

Write a PHP program to connect to a database and retrieve data from a table and display it in a page. [5]

The following program uses MySQLi to connect to a MySQL database, run a SELECT query and display the results in an HTML table.

<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "college";

// 1. Connect to the database
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 2. Run a query to retrieve data
$sql = "SELECT id, name, email FROM students";
$result = $conn->query($sql);

// 3. Display the data
if ($result && $result->num_rows > 0) {
    echo "<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th></tr>";
    while ($row = $result->fetch_assoc()) {
        echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['email']}</td></tr>";
    }
    echo "</table>";
} else {
    echo "No records found.";
}

$conn->close();
?>

Steps:

  1. Create a connection with new mysqli() and check for errors.
  2. Execute a SELECT query with $conn->query().
  3. Loop over the result set with fetch_assoc() and print each row inside an HTML table.
  4. Close the connection with $conn->close().
phpmysqldatabase
8short5 marks

How can you define a class and object in PHP? Illustrate with example. [5]

Class - A class is a blueprint/template that defines properties (variables) and methods (functions) shared by its objects. It is declared with the class keyword.

Object - An object is an instance of a class created at runtime using the new keyword. Each object has its own copy of the class's properties.

Example

<?php
// Defining a class
class Student {
    public $name;
    public $rollNo;

    // Constructor
    public function __construct($name, $rollNo) {
        $this->name = $name;
        $this->rollNo = $rollNo;
    }

    // Method
    public function display() {
        echo "Name: " . $this->name . ", Roll No: " . $this->rollNo;
    }
}

// Creating an object (instance) of the class
$s1 = new Student("Sita", 101);
$s1->display();   // Output: Name: Sita, Roll No: 101
?>

Explanation:

  • The Student class declares two properties and a display() method.
  • $this refers to the current object inside the class.
  • new Student(...) creates an object $s1; members are accessed with the -> operator.
phpoopclass-object
9short5 marks

Write a PHP program that will read two input strings in variables fname and lname and display the concatenation of fname and lname. [5]

PHP concatenates strings using the dot (.) operator. The two strings can be read from an HTML form via $_POST.

<!DOCTYPE html>
<html>
<body>
<form method="post" action="">
    First name: <input type="text" name="fname"><br>
    Last name:  <input type="text" name="lname"><br>
    <input type="submit" name="submit" value="Submit">
</form>

<?php
if (isset($_POST["submit"])) {
    $fname = $_POST["fname"];
    $lname = $_POST["lname"];

    // Concatenate the two strings (with a space between)
    $fullName = $fname . " " . $lname;

    echo "Full Name: " . $fullName;
}
?>
</body>
</html>

Explanation: the form reads fname and lname into $_POST; the . operator joins them into $fullName, which is then displayed. (If no form is needed, the variables can simply be assigned values directly and concatenated.)

phpstringsconcatenation
10short5 marks

How can you define a variable in PHP? Illustrate with example. [5]

Defining a variable in PHP

In PHP a variable starts with a dollar sign $ followed by the variable name. PHP is loosely (dynamically) typed, so you do not declare a data type - the type is decided automatically from the value assigned. Rules for variable names:

  • Must start with $ followed by a letter or underscore.
  • The name can contain letters, digits and underscores (no spaces or special characters).
  • Variable names are case-sensitive ($age and $Age are different).

Example

<?php
$name = "Hari";      // string
$age = 21;            // integer
$price = 99.50;       // float
$isStudent = true;    // boolean

echo "Name: $name <br>";
echo "Age: $age <br>";
echo "Price: $price <br>";
var_dump($isStudent);  // bool(true)
?>

Explanation: each variable is created simply by assigning a value with =. The same variable can later hold a value of a different type because PHP determines the type at runtime.

phpvariables
11short5 marks

How is conversion between arrays and variables done? [5]

PHP provides built-in functions to convert between a set of individual variables and an array.

1. Variables to an array - compact()

compact() takes variable names (as strings) and builds an associative array whose keys are the variable names and values are their contents.

<?php
$name = "Gita";
$age = 20;
$city = "Pokhara";

$arr = compact("name", "age", "city");
print_r($arr);
// Array ( [name] => Gita [age] => 20 [city] => Pokhara )
?>

2. Array to variables - extract()

extract() takes an associative array and creates a variable for each key, assigning the corresponding value.

<?php
$data = array("name" => "Gita", "age" => 20, "city" => "Pokhara");
extract($data);

echo $name;   // Gita
echo $age;    // 20
echo $city;   // Pokhara
?>

3. The list() construct can also assign array elements to several variables at once:

list($a, $b, $c) = array(10, 20, 30); // $a=10, $b=20, $c=30

Summary: compact() converts variables into an array, extract() converts an associative array into variables, and list() unpacks an indexed array into separate variables.

phparraystype-conversion
12short5 marks

Write a PHP program to illustrate string patterns using regular expressions. [5]

Regular expressions describe search patterns for matching, searching and replacing text. PHP uses PCRE (Perl-Compatible Regular Expression) functions such as preg_match(), preg_match_all() and preg_replace().

<?php
$text = "Contact: ram@example.com, phone 9841000000";

// 1. preg_match - check if a pattern exists
$emailPattern = "/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/";
if (preg_match($emailPattern, $text, $match)) {
    echo "Email found: " . $match[0] . "<br>";
}

// 2. preg_match_all - find all matches (e.g. all digits groups)
preg_match_all("/[0-9]+/", $text, $numbers);
echo "Numbers: ";
print_r($numbers[0]);
echo "<br>";

// 3. preg_replace - replace a pattern
$clean = preg_replace("/[0-9]/", "*", $text);
echo "Masked: " . $clean;
?>

Explanation:

  • preg_match() returns 1 if the pattern matches and stores the match in $match.
  • preg_match_all() finds every occurrence of the pattern.
  • preg_replace() replaces all matches of the pattern with the given string.
  • Patterns are enclosed in delimiters (here /.../) and use metacharacters such as +, ., [] and {}.
phpregular-expressionsstrings

Frequently asked questions

Where can I find the BSc CSIT (TU) BIT Web Technology II (BIT301) – 5th Semester (Model) question paper 2079?
The full BSc CSIT (TU) BIT Web Technology II (BIT301) – 5th Semester (Model) 2079 (model) question paper is available free on Kekkei. You can read every question online and attempt the paper under timed exam conditions.
Does the BIT Web Technology II (BIT301) – 5th Semester (Model) 2079 paper come with solutions?
Yes. Every question on this BIT Web Technology II (BIT301) – 5th Semester (Model) past paper includes a step-by-step solution, plus instant AI feedback when you attempt it on Kekkei.
How many marks is the BSc CSIT (TU) BIT Web Technology II (BIT301) – 5th Semester (Model) 2079 paper?
The BSc CSIT (TU) BIT Web Technology II (BIT301) – 5th Semester (Model) 2079 paper carries 60 full marks and is meant to be completed in 180 minutes, across 12 questions.
Is practising this BIT Web Technology II (BIT301) – 5th Semester (Model) past paper free?
Yes — reading and attempting this BIT Web Technology II (BIT301) – 5th Semester (Model) past paper on Kekkei is completely free.