SS2 RAI First Term Scheme of Work
SS2 RAI First Term Scheme of Work
WEEK TOPIC
1 Introduction, What is PHP, PHP Server Setup
2 Your first PHP page, Comment your scripts, Variables and Data
Types, Constants, Operators
It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!
It is deep enough to run large social networks!
It is also easy enough to be a beginner's first server-side language!
With PHP you are not limited to output HTML. You can output images or PDF files. You can also
output any text, such as XHTML and XML.
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
PHP Installation
What Do I Need?
To start using PHP, you can:
Just create some .php files, place them in your web directory, and the server will automatically
parse them for you.
You can edit PHP code, and view the result in your browser.
Try this:
<?php
$txt = "PHP";
echo "I love $txt!";
?>
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:
Example
A simple .php file with both HTML code and PHP code:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
In the example below, all three echo statements below are equal and legal:
Example
ECHO is the same as echo:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Example
$COLOR is not same as $color:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
?>
</body>
</html>
Week Two
TOPIC: YOUR FIRST PHP PAGE, COMMENT YOUR SCRIPTS, VARIABLES AND DATA
TYPES, CONSTANTS, OPERATORS
LESSON OBJECTIVES: By the end of the lessons, students should be able to:
1. create and execute a basic PHP file, utilizing PHP tags to embed PHP code within an HTML page and displaying
output using the echo statement. (Your First PHP Page)
2. use single-line and multi-line comments effectively to document their PHP code. They will demonstrate the
ability to explain code functionality, provide clear annotations, and disable code sections temporarily for
debugging purposes. (2. Comment Your Scripts).
3. declare and initialize variables in PHP, understanding and utilizing different data types (string, integer, float,
boolean, array, object, null) appropriately. They will show proficiency in type juggling and type casting to
manage and manipulate data effectively. (Variables and Data Types)
4. define and use constants in PHP to store fixed values that should not change throughout the script. They will
demonstrate understanding of the immutability of constants, proper naming conventions, and use of
constants in various scenarios such as configuration settings. (Constants).
5. apply various PHP operators (arithmetic, assignment, comparison, logical) in their code. They will show
competency in performing mathematical operations, comparing values, assigning values, and combining
conditions in control structures. (Operators)
CONTENT:
To create your first PHP page, you'll need a server with PHP installed. If you're working locally, you can use a tool
like XAMPP or WAMP to set up a local server.
Steps:
Open the file in a text editor and add the following code:
<?php
?>
Explanation:
i. <?php and ?> are the PHP tags used to indicate the start and end of PHP code.
ii. echo is a PHP statement used to output text to the browser. In this case, it will display "Hello, World!".
Comments your scripts in PHP are lines of text within the code that are ignored by the PHP interpreter during
execution. They are used to explain the code, making it easier for others (or yourself) to understand your code
when revisiting it. Good commenting practices are crucial for maintaining clear, readable, and maintainable code.
Types of Comments:
A single-line comment in PHP is a type of comment that occupies only one line and is used to annotate or explain
a specific part of the code. The PHP interpreter ignores these comments, meaning they do not affect the
execution of the program. Single-line comments are helpful for briefly explaining what a particular line of code
does.
1. Using //:
2. Using #:
Summary of Single-line comments are ideal for short, quick explanations or notes within your code.
Multi-line comments in PHP are used to annotate or explain sections of code that require more detailed
explanations, spanning across multiple lines. Multi-line comments in PHP are enclosed between /* and */.
Anything between these markers is ignored by the PHP interpreter.
Examples
/* This is a multi-line comment. It can span multiple lines, making it useful for longer explanations.
*/ $z = 15;
Example:
/*
*/
/*
*/
echo "Hello!";
Summary of multi-line comments are essential for providing detailed documentation and explanations in your
PHP scripts. They help make complex or lengthy sections of code more understandable and maintainable.
A variable in PHP is used to store data that can be manipulated or retrieved throughout a script. Variables in PHP
are dynamic, meaning they can hold different types of data at different times.
i. A variable starts with the $ sign, followed by the name of the variable
ii. A variable name must start with a letter or the underscore character
iv. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
v. Variable names are case-sensitive ($age and $AGE are two different variables)
Example:
Output Variables
The PHP echo statement is often used to output data to the screen.
$txt = "W3Schools.com";
Example shows how to produce the same output as the example above:
$txt = "W3Schools.com";
$x = 5;
$y = 4;
echo $x + $y;
data type
Data type refers to the classification of data that determines the type of values a variable can hold. Data types
dictate what kind of operations can be performed on the data, how the data is stored in memory, and how it
behaves when manipulated.
$age = 25;
$price = 19.99;
$is_student = true;
v. Null: A special data type that can have only one value: NULL.
$var = null;
SUB-TOPIC 4. CONSTANTS
A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Defining Constants:
echo SITE_NAME;
Explanation:
SITE_NAME is the name of the constant, and "My Website" is the value.
Constants are automatically global and can be used across the entire script.
Syntax
echo GREETING;
echo greeting;
SUB-TOPIC 5. Operators
Types of Operators:
$diff = 10 - 5; // Subtraction
$quot = 10 / 2; // Division
php
Copy code
$x = 10; // Assigns 10 to $x
$x += 5; // Adds 5 to $x (same as $x = $x + 5)
php
Copy code
$x == $y; // Equal to
php
Copy code
$x || $y; // Or
!$x; // Not
This should give you a foundational understanding of PHP basics including your first page, commenting, variables,
data types, constants, and operators.
EXERCISE
1. What is a correct syntax to define a constant? A. constant ("MESSAGE", "Welcome to my home"); B. constant
"MESSAGE" = "Welcome to my home"; C. define("MESSAGE", "Welcome to my home");
2. What data type is the $x variable below: $x = true; A. String B. Float C. Boolean D. Integer
3. Which one is NOT a legal PHP comment: A. # comment goes here B. // comment goes here C. '' comment goes
here D. /* comment goes here */
4. Which one is a correct syntax for incrementing $x by 1:Which one is a correct syntax for A. $x + 1; B. $x++; C. 1
+ $x;
5. What will be the output of the following code:
$x = 5;
echo 'The price is $x';
A. The price is 5B. The price is C.The price $x
Weekthree
PHP include and required
include: This is used to include and evaluate a specified file.If the file is not found, it generates a warning
but the script continues to run.
Syntax: include 'header.php';
require: This is similar to include, but if the file is not found, it generates a fatal error and stops the
script.
Syntax: require ‘header.php’;
Example:
<?php
// header.php
echo “<h1>Welcome to My Website</h1>”;
// main.php
<?php
include ‘header.php’;
echo “<p>This is the main content.</p>”;
Conditional Statements
They allow execution of different code blocks based on certain conditions.
Types include: `if`, `else`, `elseif`, `switch`.
<?php
if ($age >= 18) {
echo “You are an adult.”;
}
if...else Statement:
It executes one block of code if a condition is true, another if it is false.
<?php
if ($age >= 18) {
echo “You are an adult.”;
} else {
echo “You are a minor.”;
}
if...elseif...else Statement:
It executes different blocks of code based on multiple conditions.
<?php
if ($score >= 90) {
echo “Grade: A”;
} elseif ($score >= 80) {
echo “Grade: B”;
} else {
echo “Grade: C”;
}
PHP Loops
In PHP, a loop is a control structure that allows you to execute a block of code repeatedly based on a
condition. Loops are useful for tasks that require repetitive actions, such as iterating over arrays or
performing a task a specific number of times.
PHP supports four main types of loops.
Example
<?php
$i = 1;
while ($i<= 5) {
echo “The number is: $i<br>”;
$i++;
}
Explanation: In this example, the loop will run as long as $i is less than or equal to 5. The value of $i is
incremented by 1 in each iteration. The loop will print numbers from 1 to 5.
for Loop:
Repeats a block of code a specified number of times.
Syntax
for (initialization; condition; increment) {
// code to be executed
}
Example
<?php
for ($i = 1; $i<= 5; $i++) {
echo “The number is: $i<br>”;
}
Explanation: Here, the loop starts with $i set to 1, runs as long as $i is less than or equal to 5, and
increments $i by 1 after each iteration. The loop will also print numbers from 1 to 5.
<?php
$colors = array(”red”, “green”, “blue”);
foreach ($colors as $color) {
echo “The color is: $color <br>”;
}
//The loop will print each color in the array.
do...while Loop: This executes a block of code once, and then repeats as long as a condition is true.
<?php
$i = 1;
do {
echo “The number is: $i<br>”;
$i++;
} while ($i<= 5);
Summary
while: Repeats as long as the condition is true.
for: Repeats a specific number of times.
foreach: Iterates over each element in an array.
do...while: Executes at least once, then repeats as long as the condition is true.
Exercises
1. Age Checker: Write a PHP script that checks a user’s age and prints whether they are a minor, an
adult, or a senior citizen.
2. Grade Calculator: Write a PHP script that takes a student’s score and prints their grade (A, B, C, D,
E or F.) based on the score.
3. Login System: Write a PHP script that checks a username and password against predefined values
and prints a welcome message if they match, or an error message if they don’t.
4. Sum of Numbers: Write a PHP script using a for loop to calculate the sum of numbers from 1 to
100.
Weekfour
What is an Array?
An array is a special variable that can hold many values under a single name, and you can access
the values by referring to an index number or name.
An array stores multiple values in one single variable:$cars=array("Volvo","BMW","Toyota");
1. PHP Indexed Arrays: In indexed arrays each item has an index number. By default, the first
item has index 0, the second item has item 1, etc.
Create and display an indexed array:
Example
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
Change Value
To change the value of an array item, use the index number:
Example Change the value of the second item:
$cars=array("Volvo","BMW","Toyota");
$cars[1]="Ford";
var_dump($cars);
Index Number
The key of an indexed array is a number, by default the first item is 0 and the second is 1 etc., but
there are exceptions.
New items get the next index number, meaning one higher than the highest existing index.
So if you have an array like this:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
And if you use the array_push() function to add a new item, the new item will get the index
3:
Example
array_push($cars,"Ford");
var_dump($cars);
But if you have an array with random index numbers, like this:
$cars[5]="Volvo";
$cars[7]="BMW";
$cars[14]="Toyota";
And if you use the array_push() function to add a new item, what will be the index number
of the new item?
Example
array_push($cars,"Ford");
var_dump($cars);
Change Value
To change the value of an array item, use the key name:
Example
Change the year item:
$car=array("brand"=>"Ford","model"=>"Mustang","year"=>1964);
$car["year"]=2024;
var_dump($car);
Multiple Lines
Line breaks are not important, so an array declaration can span multiple lines:
Example
$cars=[
"Volvo",
"BMW",
"Toyota"
];
Array Keys
When creating indexed arrays the keys are given automatically, starting at 0 and increased by 1
for each item, so the array above could also be created with keys:
Example
$cars=[
0=>"Volvo",
1=>"BMW",
2=>"Toyota"
];
Indexed arrays are the same as associative arrays, but associative arrays have names instead of
numbers
Example
$myCar=[
"brand"=>"Ford",
"model"=>"Mustang",
"year"=>1964
];
Week Five
Functions
i. Define functions
ii. Describe 2 types of function
iii. Describe function argument
A function is a block of code with name, meant to perform a specific task, e.g. performing calculation or string, or
array handling. It can be used repeatedly in a program.
A function is created or defined using the function keyword
Syntax /*function definition*/
function functionName(parameter1, parameter2, ...) //function header
{
Statement(s) to be executed // php function example code block
[ return returingValue;] //optional
}
Here is an explanation of the different parts of a PHP function:
function: This keyword signals the beginning of the function definition.
functionName: The name of the function. It should be unique and describe the purpose of the function.
parameter1, parameter2, …: Parameters are values that are passed to the PHP function when it’s called.
They’re optional, and you can use as many as you need.
code block: Code executes a task or performs the desired operations.
return result: This is optional. If the function is to return a result, use the return statement.
A function will not execute automatically when a page loads. For example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>Page Title</title>
</head>
<body>
<?php
function wishHi()
{
echo “Hi”,”<br/>”;
}
?>
</body>
</html>
copy code into your editor, then open in the localhost of your browser, it won’t display until the function
defined is called
</head>
<body>
<?php
function wishHi()
{
echo “Hi”,”<br/>”;
}
wishHi();
?>
</body>
</html>
Example 2.
<!DOCTYPE html>
<html>
<body>
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
</body>
</html>
Why are functions created?
i. For manageability (i.e. to break down a larger problem into smaller tasks or modules)
ii. For reusability (i.e. once a function is defined, it can be used multiple times)
iii. For abstraction (i.e. hiding the way tasks are done, hiding unnecessary information from user)
PHP functions can be built-in or user defined:
PHP built-in functions? Built-in functions are pre-defined functions that are included within the core PHP
language. These functions are used without any special requirements or additional installation.
While, User-defined functions are custom functions that developers create.
Regardless of whether a PHP function is built-in or user-defined;
iv. A function name must start with a letter or an underscore.
v. Function names are NOT case-sensitive.
vi. It is also important to give the function a name that reflect what the function does.
vii. Calling functions must always start with the keyword function
viii. PHP code must be contained within curly brackets {}
ix. Functions can be called by name, followed by arguments within parentheses.
<?php
greet();
?>
Function arguments are variables that are passed to a function when it’s called. These arguments provide
input(information) to the function and can be used within its code to perform specific actions or calculations.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you
want, just separate them with a comma.
If the function takes arguments, then pass them within the parentheses. For instance, if you have a function
called sum(), you can call it like this:
<?php
?>
The following example has a function with one argument ($fname). When the familyName() function is called,
we also pass along a name, e.g. ("Jani"), and the name is used inside the function, which outputs several
different first names, but an equal last name:
<?php
function familyName($fname) {
echo "$fnameRefsnes.<br>";
}
familyName("Jani");
familyName("Borge");
?>
To pass a variable to a function, start with defining the function and specifying its parameters – like so:
<?php
$name = "Alice";
function greet($name) {
?>
Here, $name is the function argument. When greet() is called, its value, “Alice” is passed as an argument and
assigned to the $name variable within the function.
Solution
Create separate functions for addition, subtraction, multiplication, and division. Each function should take two parameters
and return the result of the operation.
Solutions
1. <?php
2. // Addition function
3. function add($a, $b) {
4. return $a + $b;
5. }
6.
7. // Subtraction function
8. function subtract($a, $b) {
9. return $a - $b;
10. }
11.
12. // Multiplication function
13. function multiply($a, $b) {
14. return $a * $b;
15. }
16.
17. // Division function
18. function divide($a, $b) {
19. if ($b == 0) {
20. return "Error: Division by zero";
21. }
22. return $a / $b;
23. }
24. ?>
3. Use HTML to create a form where users can input two numbers and select an operation.
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<form method="post">
Number 1: <input type="text" name="num1" required><br>
Number 2: <input type="text" name="num2" required><br>
Operation:
<select name="operation">
<option value="add">Add</option>
<option value="subtract">Subtract</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select><br>
<input type="submit" value="Calculate">
</form>
4. To Process the form submission using PHP and display the result based on the selected operation.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operation = $_POST['operation'];
switch ($operation) {
case "add":
$result = add($num1, $num2);
break;
case "subtract":
$result = subtract($num1, $num2);
break;
case "multiply":
$result = multiply($num1, $num2);
break;
case "divide":
$result = divide($num1, $num2);
break;
default:
$result = "Invalid operation";
}
Week Six
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. Unlike
a cookie, the information is not stored on the users computer.
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The
computer knows who you are. It knows when you start the application and when you end. But on the internet there is one
problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some
session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Another way to show all the session variable values for a user session is to run the following code:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
PHP Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both
create and retrieve cookie values.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset()
function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded
when received (to prevent URLencoding, use setrawcookie() instead).
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:
The PHP code to read the file and write it to the output buffer is as follows (the readfile() function returns the
number of bytes read on success):
<?php
echo readfile("webdictionary.txt");
?>
The readfile() function is useful if all you want to do is open up a file and read its contents.
The next chapters will teach you more about file handling.
PHP File Create/Write
In this chapter we will teach you how to create and write to a file on the server.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or
appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the same directory where the
PHP code resides:
Example
The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to
be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") ordie("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string $txt that first
contained "John Doe" and second contained "Jane Doe". After we finished writing, we closed the file using the
fclose() function.
If we open the "newfile.txt" file it would look like this:
John Doe
Jane Doe
The first parameter of fread() contains the name of the file to read from and the second parameter specifies the
maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") ordie("Unable to open file!");
echofgets($myfile);
fclose($myfile);
?>
The example below reads the "webdictionary.txt" file character by character, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") ordie("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echofgetc($myfile);
}
fclose($myfile);
?>
Week Seven
Midterm Break
Week Eight
Robotics
Week Nine
Robotics