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.
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 answerHide 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
| Concept | Description |
|---|---|
extends | Used to inherit parent class into child class |
parent::__construct() | Calls the constructor of the parent class |
| Inherited method | eat() is defined in Animal but used by Dog |
| Method Overriding | display() is redefined in Dog class |
| Child-specific method | bark() belongs only to Dog class |
2079 · 5 marks
How can you define class and objects in PHP? Write a PHP script to create class and its object. [5]
Inserting Multiple Data
2082 · 5 marks
Write a PHP program to show insertion of multiple data into a database table. [5]
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 answerHide 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
| Element | Validation Rule |
|---|---|
username | Required, length >= 5 |
password | Required, starts with digit, ends with $ |
gender | Radio 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)
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]
Functions
2081 · 5 marks
Write a PHP function add that takes two arguments as an input and return their sum. [5]
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]
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]
Cookies and Sessions
2081 · 5 marks
Define cookie. Write a PHP program to create and retrieve a cookie. [5]
Show solved answerHide answer
Cookie: Definition and PHP Program
Definition of Cookie
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 Program to Create and Retrieve a Cookie
Step 1: Create (Set) a Cookie
<?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!";
?>
Step 2: Retrieve (Read) a Cookie
<?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 / Variable | Purpose |
|---|---|
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() + 86400 | Sets expiry to 1 day (86400 seconds) from now |
Note:
setcookie()must be called before any HTML output, otherwise the cookie will not be set.
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 answerHide answer
PHP Server-Side Script: Inserting and Selecting Values from Database
Assumptions
- Server:
localhost - Username:
root - Password: `` (empty)
- Database:
webTech - Table:
studentswith columnsid,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
| Step | Description |
|---|---|
| 1 | Set server credentials (localhost, root, empty password, webTech DB) |
| 2 | Use mysqli_connect() to create connection; check with if(!$conn) |
| 3 | Create students table if it does not already exist |
| 4 | Write INSERT SQL query and execute using mysqli_query() |
| 5 | Write SELECT SQL query (SELECT * FROM students) and execute |
| 6 | Use mysqli_num_rows() to check if rows exist; loop with mysqli_fetch_assoc() to display each row |
| 7 | Close 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 andmysqli_query()for executing SQL statements. Thedie()function stops execution if the connection fails, so noelseblock is needed after it.
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]
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]
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]
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]
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]
Make Unit 6 stick
Practice CSC329 with flashcards & quizzes