6 Server Side Scripting Using Php

Web Technology · Unit 6 · 8 hrs

Server Side Scripting using PHP

Exam-focused notes for Server Side Scripting using PHP (Web Technology, CSC329): what the TU syllabus asks and how it has actually been tested, with 16 solved past questions from this unit.

Server Side Scripting using PHP in short

PHP is the server-side counterpart to the JavaScript covered earlier in this course: a script that runs on the web server, builds the HTML that is actually sent to the browser, and is what lets a page talk to a database. This unit covers PHP's syntax and language features before moving into forms, sessions, and safe database access.

Server Side Scripting using PHP: notes

PHP Syntax

PHP (Hypertext Preprocessor) is a widely used, free, server-side scripting language for building dynamic and interactive web pages, and a long-standing alternative to competitors such as Microsoft's ASP. A .php file can freely mix plain text, HTML, CSS, JavaScript and PHP code; only the PHP portions are executed on the server, and the result, ordinary HTML, is what reaches the browser. A block of PHP code starts with <?php and ends with ?>, and a single file can contain multiple such blocks. Output is written with echo or print, which behave almost identically. Comments use // or # for a single line and /* ... */ for multiple lines.

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

PHP is popular because it runs on almost any platform (Windows, Linux, Unix), is compatible with virtually every web server, supports a wide range of databases, and is free and comparatively easy to learn.

Variables

A PHP variable starts with a $ sign followed by the variable's name, and it acts as a container for a value. Variable names must start with a letter or an underscore, cannot start with a digit, and are case-sensitive, so $Name and $name are different variables.

<?php
$txt = "Hello World!";
$x = 5;
$y = 10.5;
?>

Data Types

PHP supports several core data types. String holds a sequence of characters inside single or double quotes. Integer holds a whole, non-decimal number. Float (or double) holds a number with a decimal point. Boolean holds one of exactly two states, true or false. Array stores multiple values under one variable name. NULL is a special type with only one possible value, NULL, meaning the variable has deliberately been given no value.

<?php
$x = "Hello World!";   // string
$x = 5985;             // integer
$x = 10.365;           // float
$x = true;             // boolean
$cars = array("Volvo", "BMW", "Toyota");  // array
$x = null;             // null
?>

Strings

A PHP string is text inside quotes; single quotes and double quotes both work, with double quotes additionally interpreting variables and certain escape sequences inside the string. PHP supplies a large library of string functions: strlen() returns a string's length; str_word_count() counts its words; strrev() reverses it; strpos() searches for one string inside another and returns the position of the first match (or false if not found); str_replace() substitutes one piece of text for another.

<?php
echo strlen("Hello World");                    // 11
echo str_word_count("Hello World.");            // 2
echo strrev("Hello World.");                    // .dlroW olleH
echo strpos("Hello World", "World");             // 6
echo str_replace("World", "Dolly", "Hello World."); // Hello Dolly.
?>

Constants

A PHP constant is an identifier for a value that, once defined, can never be changed or removed, and unlike a variable, a constant is automatically available everywhere in a script (global scope) without special declaration. define(name, value, case_insensitive) creates one, and the optional third argument controls whether the name is treated case-insensitively (default false). The const keyword is the newer alternative: it defines a constant at compile time, is always case-sensitive, and is generally faster than define().

<?php
define("GREETING", "Welcome to the site");
echo GREETING;

const MESSAGE = "Hello const";
echo MESSAGE;
?>

Operators

PHP groups its operators into several families: arithmetic (+, -, *, /, %), assignment (=, +=, -=, and so on), comparison (==, ===, !=, <, >), logical (&&, ||, !), increment/decrement (++, --), and the string concatenation operator .. Operators can also be grouped by how many operands they act on: unary (a single operand, such as -$x), binary (two operands, such as $x + $y), and ternary (a condensed conditional, condition ? valueIfTrue : valueIfFalse).

<?php
$x = 10; $y = 3;
echo $x % $y;                 // 1
echo ($x > $y) ? "bigger" : "smaller";  // bigger
?>

What this unit covers

  • PHP Syntax
  • Variables
  • Data Types
  • Strings
  • Constants
  • Operators
  • Control structure
  • Functions
  • Array
  • Creating Class and Objects
  • PHP Forms
  • Accessing Form Elements
  • Form Validation
  • Events
  • Cookies and Sessions
  • Working with PHP and MySQL
  • Connecting to Database
  • Creating, Selecting, Deleting, Updating Records in a table
  • Inserting Multiple Data
  • Introduction to CodeIgniter, Laravel, Wordpress etc.

Creating Class and Objects

2082 · 5 marks

Write a PHP program to demonstrate the concept of inheritance. [5]

Show solved answer

PHP Program to Demonstrate Inheritance

Concept of Inheritance in PHP

Inheritance is an OOP concept where a child class (derived class) acquires the properties and methods of a parent class (base class) using the extends keyword. This promotes code reusability.


PHP Program

<?php

// Parent Class (Base Class)
class Animal {
    public $name;
    public $color;

    // Constructor of Parent Class
    public function __construct($name, $color) {
        $this->name  = $name;
        $this->color = $color;
    }

    // Method in Parent Class
    public function eat() {
        echo $this->name . " eats food. ";
    }

    public function display() {
        echo "Name  : " . $this->name  . " ";
        echo "Color : " . $this->color . " ";
    }
}

// Child Class (Derived Class) - inherits from Animal
class Dog extends Animal {
    public $breed;

    // Constructor of Child Class
    public function __construct($name, $color, $breed) {
        // Call parent constructor using parent keyword
        parent::__construct($name, $color);
        $this->breed = $breed;
    }

    // Method specific to Child Class
    public function bark() {
        echo $this->name . " says: Woof! Woof! ";
    }

    // Overriding parent method (Method Overriding)
    public function display() {
        parent::display();
        echo "Breed : " . $this->breed . " ";
    }
}

// Creating object of Parent Class
echo "<b>--- Animal Object ---</b> ";
$animal = new Animal("Cat", "White");
$animal->display();
$animal->eat();

echo " ";

// Creating object of Child Class
echo "<b>--- Dog Object (Child Class) ---</b> ";
$dog = new Dog("Tommy", "Brown", "Labrador");
$dog->display();   // Calls overridden display()
$dog->eat();       // Inherited from Animal
$dog->bark();      // Own method of Dog

?>

Output

--- Animal Object ---
Name  : Cat
Color : White
Cat eats food.

--- Dog Object (Child Class) ---
Name  : Tommy
Color : Brown
Breed : Labrador
Tommy eats food.
Tommy says: Woof! Woof!

Key Points Demonstrated

ConceptDescription
extendsUsed to inherit parent class into child class
parent::__construct()Calls the constructor of the parent class
Inherited methodeat() is defined in Animal but used by Dog
Method Overridingdisplay() is redefined in Dog class
Child-specific methodbark() belongs only to Dog class
Open this answer on its own page →

2079 · 5 marks

How can you define class and objects in PHP? Write a PHP script to create class and its object. [5]

A class is a "blueprint" for an object, used as a code template to generate objects. It contains the code for properties (variables) and methods (functions). A class is defined using the class keyword, followed by the class name and a pair of curly braces { }. All properties and methods go inside...

Open this answer on its own page →

Inserting Multiple Data

2082 · 5 marks

Write a PHP program to show insertion of multiple data into a database table. [5]

The program follows the standard MySQLi procedural approach as described in the curriculum notes: 1. Establish a database connection using mysqliconnect() 2. Select the target database 3. Insert multiple rows using multiple INSERT SQL queries (or a single multi-row INSERT) 4. Check success/failur...

Open this answer on its own page →

Form Validation

2082 · 5 marks

Create a PHP form with form elements. Write a program to perform form validation. Use your own assumptions for the validation. [5]

Show solved answer

PHP Form with Validation

Assumptions for Validation:

  • Username: required, minimum 5 characters
  • Password: required, must start with a digit and end with $
  • Gender (radio button): must be selected
  • Hobbies (checkbox): at least one must be checked

Complete PHP Program

<?php
// Initialize variables
$username = $password = $gender = "";
$hobbies = [];
$errors = [];
$success = "";

// Process form on submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Username Validation
    if (empty($_POST["username"])) {
        $errors[] = "Username is required.";
    } else {
        $username = trim($_POST["username"]);
        if (strlen($username) < 5) {
            $errors[] = "Username must be at least 5 characters long.";
        }
    }

    // Password Validation
    if (empty($_POST["password"])) {
        $errors[] = "Password is required.";
    } else {
        $password = trim($_POST["password"]);
        // Must start with a digit and end with $
        if (!preg_match('/^\d/', $password) || !preg_match('/\$$/', $password)) {
            $errors[] = "Password must start with a digit and end with '$'.";
        }
    }

    // Gender Validation (Radio Button)
    if (empty($_POST["gender"])) {
        $errors[] = "Please select your gender.";
    } else {
        $gender = $_POST["gender"];
    }

    // Hobbies Validation (Checkbox)
    if (empty($_POST["hobbies"])) {
        $errors[] = "Please select at least one hobby.";
    } else {
        $hobbies = $_POST["hobbies"];
    }

    // If no errors, show success
    if (empty($errors)) {
        $success = "Form submitted successfully! Welcome, " . htmlspecialchars($username) . ".";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>PHP Form Validation</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 30px; }
        .error { color: red; }
        .success { color: green; font-weight: bold; }
        label { display: inline-block; width: 120px; }
        input[type="text"], input[type="password"] {
            padding: 5px;
            width: 200px;
        }
        .form-group { margin: 10px 0; }
    </style>
</head>
<body>

<h2>Registration Form</h2>

<!-- Display Errors -->
<?php if (!empty($errors)): ?>
    <ul class="error">
        <?php foreach ($errors as $error): ?>
            <li><?php echo $error; ?></li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

<!-- Display Success -->
<?php if (!empty($success)): ?>
    <p class="success"><?php echo $success; ?></p>
<?php endif; ?>

<!-- HTML Form -->
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

    <!-- Username -->
    <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"
               value="<?php echo htmlspecialchars($username); ?>">
    </div>

    <!-- Password -->
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" id="password" name="password">
    </div>

    <!-- Gender (Radio Buttons) -->
    <div class="form-group">
        <label>Gender:</label>
        <input type="radio" name="gender" value="Male"
            <?php echo ($gender == "Male") ? "checked" : ""; ?>> Male
        <input type="radio" name="gender" value="Female"
            <?php echo ($gender == "Female") ? "checked" : ""; ?>> Female
        <input type="radio" name="gender" value="Other"
            <?php echo ($gender == "Other") ? "checked" : ""; ?>> Other
    </div>

    <!-- Hobbies (Checkboxes) -->
    <div class="form-group">
        <label>Hobbies:</label>
        <input type="checkbox" name="hobbies[]" value="Reading"
            <?php echo (in_array("Reading", $hobbies)) ? "checked" : ""; ?>> Reading
        <input type="checkbox" name="hobbies[]" value="Gaming"
            <?php echo (in_array("Gaming", $hobbies)) ? "checked" : ""; ?>> Gaming
        <input type="checkbox" name="hobbies[]" value="Coding"
            <?php echo (in_array("Coding", $hobbies)) ? "checked" : ""; ?>> Coding
        <input type="checkbox" name="hobbies[]" value="Travelling"
            <?php echo (in_array("Travelling", $hobbies)) ? "checked" : ""; ?>> Travelling
    </div>

    <!-- Submit Button -->
    <div class="form-group">
        <input type="submit" value="Register">
    </div>

</form>

</body>
</html>

Key Points Explained

ElementValidation Rule
usernameRequired, length >= 5
passwordRequired, starts with digit, ends with $
genderRadio button must be selected
hobbies[]At least one checkbox must be checked
  • $_SERVER["REQUEST_METHOD"] == "POST" checks if the form is submitted.
  • preg_match() is used for pattern-based password validation.
  • htmlspecialchars() prevents XSS attacks on output.
  • empty($errors)
Open this answer on its own page →

PHP Forms

2081 · 10 marks

Write a PHP program to create a form. Create an insertdb() method to insert the form values into a database table and display() to display the database table value.[10]

--- Before running the program, create the table in MySQL: --- Part Description ------ mysqliconnect() Creates connection to MySQL using procedural approach insertdb($conn, ...) Takes form values as parameters and runs INSERT query display($conn) Runs SELECT query and prints all rows in an HTML t...

Open this answer on its own page →

Functions

2081 · 5 marks

Write a PHP function add that takes two arguments as an input and return their sum. [5]

Based on the PHP Functions and Function Arguments concepts A PHP function is declared using the function keyword, and arguments are passed inside the parentheses separated by commas. --- --- --- Part Description ------ function add(...) Declares a user-defined function named add $num1, $num2 Two ...

Open this answer on its own page →

2080 · 5 marks

Write a PHP program that includes a function that will take two strings as input argument and print concatenation of two strings. [5]

A user-defined function declaration starts with the word function. Arguments are specified after the function name, inside the parentheses, and as many arguments as needed can be added, separated by commas. --- --- --- Step Description ------------------- function concatenateStrings($str1, $str2)...

Open this answer on its own page →

2078 · 5 marks

How can you define function in PHP? Create a function that will take two integers as argument and will return product of them. [5]

A function is a block of statements that can be used repeatedly in a program. A function will not execute immediately when a page loads; it will be executed only when it is called. Besides built-in PHP functions, we can create our own user-defined functions. Key Points: - A user-defined function ...

Open this answer on its own page →

Cookies and Sessions

2081 · 5 marks

Define cookie. Write a PHP program to create and retrieve a cookie. [5]

Show solved answer

Cookie: Definition and PHP Program

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. Cookies are used to identify users and store information between page requests. Examples of cookies include Name cookie, Date cookie, etc.

PHP can send and receive cookies.


<?php
// Setting a cookie
// setcookie(name, value, expiry_time)
$cookie_name  = "username";
$cookie_value = "JohnDoe";

// Cookie expires in 1 day (time() + 86400 seconds)
setcookie($cookie_name, $cookie_value, time() + 86400);

echo "Cookie has been set successfully!";
?>

<?php
// Retrieving the cookie
if (isset($_COOKIE["username"])) {
    echo "Cookie Found! ";
    echo "Username is: " . $_COOKIE["username"];
} else {
    echo "Cookie is not set.";
}
?>

Complete Program (Create and Retrieve in One File)

<?php
// Step 1: Create/Set the cookie
$cookie_name  = "username";
$cookie_value = "JohnDoe";

// setcookie must be called before any HTML output
setcookie($cookie_name, $cookie_value, time() + 86400); // expires in 1 day
?>

<!DOCTYPE html>
<html>
<head>
    <title>Cookie Example</title>
</head>
<body>

<?php
// Step 2: Retrieve the cookie
if (isset($_COOKIE["username"])) {
    echo "<p>Cookie Name  : username</p>";
    echo "<p>Cookie Value : " . $_COOKIE["username"] . "</p>";
} else {
    echo "<p>Cookie is not set yet. Please refresh the page.</p>";
}
?>

</body>
</html>

Output

Cookie Name  : username
Cookie Value : JohnDoe

Key Points

Function / VariablePurpose
setcookie()Creates/sets a cookie on the client's computer
$_COOKIE[]Superglobal array used to retrieve cookie values
isset()Checks whether the cookie exists before reading
time() + 86400Sets expiry to 1 day (86400 seconds) from now

Note: setcookie() must be called before any HTML output, otherwise the cookie will not be set.

Open this answer on its own page →

2080 · 5 marks

How can you handle session in PHP? [5]

A session is a way to store information (in variables) to be used across multiple pages. Unlike cookies, session data is stored on the server side. Each user gets a unique session ID which is used to identify them across requests. --- Before using session variables, you must start the session usi...

Open this answer on its own page →

Working with PHP and MySQL

2080 · 10 marks

Write a server side script in PHP to illustrate inserting and selecting values to and from database table. Create required connection using your own assumptions.[10]

Show solved answer

PHP Server-Side Script: Inserting and Selecting Values from Database

Assumptions

  • Server: localhost
  • Username: root
  • Password: `` (empty)
  • Database: webTech
  • Table: students with columns id, name, email, phone

Complete PHP Script

<?php

// Step 1: Database Connection
$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "webTech";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Step 2: Check Connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully  ";

// Step 3: Create Table (if not exists)
$createTable = "CREATE TABLE IF NOT EXISTS students (
    id     INT(6) AUTO_INCREMENT PRIMARY KEY,
    name   VARCHAR(50)  NOT NULL,
    email  VARCHAR(50)  NOT NULL,
    phone  VARCHAR(15)  NOT NULL
)";

if (mysqli_query($conn, $createTable)) {
    echo "Table ready.  ";
} else {
    echo "Error creating table: " . mysqli_error($conn) . " ";
}

// Step 4: INSERT values into the table
$name  = "Ram Sharma";
$email = "[email protected]";
$phone = "9841000000";

$insertSQL = "INSERT INTO students (name, email, phone)
              VALUES ('$name', '$email', '$phone')";

if (mysqli_query($conn, $insertSQL)) {
    echo "Record inserted successfully.  ";
} else {
    echo "Error inserting record: " . mysqli_error($conn) . " ";
}

// Step 5: SELECT values from the table
$selectSQL = "SELECT * FROM students";
$result    = mysqli_query($conn, $selectSQL);

// Step 6: Display the results
if (mysqli_num_rows($result) > 0) {
    echo " <strong>Records from students table:</strong> ";
    echo "<table border='1' cellpadding='5'>";
    echo "<tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
          </tr>";

    // Fetch each row and display
    while ($row = mysqli_fetch_assoc($result)) {
        echo "<tr>";
        echo "<td>" . $row["id"]    . "</td>";
        echo "<td>" . $row["name"]  . "</td>";
        echo "<td>" . $row["email"] . "</td>";
        echo "<td>" . $row["phone"] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "No records found.";
}

// Step 7: Close Connection
mysqli_close($conn);

?>

Step-by-Step Explanation

StepDescription
1Set server credentials (localhost, root, empty password, webTech DB)
2Use mysqli_connect() to create connection; check with if(!$conn)
3Create students table if it does not already exist
4Write INSERT SQL query and execute using mysqli_query()
5Write SELECT SQL query (SELECT * FROM students) and execute
6Use mysqli_num_rows() to check if rows exist; loop with mysqli_fetch_assoc() to display each row
7Close connection using mysqli_close()

Expected Output

Connected successfully
Table ready.
Record inserted successfully.

Records from students table:
+----+------------+-----------------+------------+
| ID | Name       | Email           | Phone      |
+----+------------+-----------------+------------+
|  1 | Ram Sharma | [email protected] | 9841000000 |
+----+------------+-----------------+------------+

Note: The procedural approach uses mysqli_connect() for connection and mysqli_query() for executing SQL statements. The die() function stops execution if the connection fails, so no else block is needed after it.

Open this answer on its own page →

2076 · 10 marks

Create web form for book search catalog. The form should contain a dropdown defining search type, a text box for search keyword, a radio button for download type true or false, now write PHP script to store data from the form into database table and also retrive the results from stored table in a new page.[10]

This solution has three files: - form.html - The search form - store.php - Stores form data into the database - retrieve.php - Retrieves and displays stored results --- --- --- --- --- Step File Action -------------------- 1 form.html User selects a search type, enters a keyword, and picks downlo...

Open this answer on its own page →

Connecting to Database

2079 · 10 marks

How database connection is created in PHP? Write a PHP program to create a form and insert values in to the database table. The form should contain at least two input fields.[10]

There are three ways of working with MySQL and PHP: 1. MySQLi (object-oriented) 2. MySQLi (procedural) 3. PDO The following three lines are always written when using localhost: Note: mysqliconnect() takes server name, username, password, and optionally the database name as parameters. die() stops...

Open this answer on its own page →

Array

2079 · 5 marks

How can you define array in PHP? Write a PHP function to create an array of type integer and print its elements. [5]

An array is a data structure that stores multiple values in a single variable. In PHP, an array can hold values of different data types (string, integer, float, etc.) under one variable name, and each element is accessed using an index (starting from 0). Syntax: Or using the short syntax (PHP 5.4...

Open this answer on its own page →

2078 · 10 marks

How do you define an Array in PHP? write a PHP script to create a multidimensional array name Product that will contain pcode, pname, and price. Initialize the array with at least three instances. Also, Write an HTML script to display the initialized values of the array in an HTML Table.[10]

As stated in the course notes: "An array is a special variable, which can hold more than one value at a time. An array can hold many values under a single name, and we can access the values by referring to an index number." --- According to the notes, PHP supports three types of arrays: Type Desc...

Open this answer on its own page →

Variables

2076 · 5 marks

How can you define variables in PHP? Define any two variable of string types and display their results after concatenation. [5]

In PHP, a variable starts with the $ sign, followed by the name of the variable. Variables are like containers for storing data. - A variable starts with the $ sign, followed by the name of the variable. - A variable name must start with a letter or the underscore character (). - A variable name ...

Open this answer on its own page →