0% found this document useful (0 votes)
11 views30 pages

SS2 RAI First Term Scheme of Work

Uploaded by

gospelokoro344
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views30 pages

SS2 RAI First Term Scheme of Work

Uploaded by

gospelokoro344
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

SS2 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

3 Include, include_once, require, require_once, Loops; Conditions


4 Arrays
5 Functions and form Data
6 Sessions, Cookies; Filesystem, Reading from a text file, Writing
to a text file
7 Mid term Break
8 Robotics
9 Robotics
10 Examination
Week one
INTRODUCTION TO PHP
What is PHP?
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open-source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

PHP is an amazing and popular language!

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!

What is a PHP File?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code is executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php"

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

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:

 Find a web host with PHP and MySQL support


 Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support


If your server has activated support for PHP you do not need to do anything.

Just create some .php files, place them in your web directory, and the server will automatically
parse them for you.

You do not need to compile anything or install any extra tools.

Because PHP is free, most web hosts offer PHP support.

Set Up PHP on Your Own PC


However, if your server does not support PHP, you must:

 install a web server


 install PHP
 install a database, such as MySQL

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.

Basic PHP Syntax


A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:


<?php

// PHP code goes here

?>

The default file extension for PHP files is ".php".

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>

<h1>My first PHP page</h1>

<?php

echo "Hello World!";

?>

</body>

</html>

Note: PHP statements end with a semicolon (;).

PHP Case Sensitivity


In PHP, keywords (e.g., if, else, while, echo, etc.), classes, functions, and user-defined functions
are not case-sensitive.

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

ECHO "Hello World!<br>";

echo "Hello World!<br>";

EcHo "Hello World!<br>";

?>

</body>

</html>

Note: However; all variable names are case-sensitive!


Look at the example below; only the first statement will display the value of
the $color variable! This is because $color, $COLOR, and $coLOR are treated as three
different variables:

Example
$COLOR is not same as $color:

<!DOCTYPE html>

<html>

<body>

<?php
$color = "red";

echo "My car is " . $color . "<br>";

echo "My house is " . $COLOR . "<br>";

echo "My boat is " . $coLOR . "<br>";

?>

</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)

SUB-TOPIC 1: . Your First PHP Page

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:

 Create a new file with a .php extension, e.g., index.php.

 Open the file in a text editor and add the following code:

<?php

echo "Hello, World!";

?>

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!".

SUB-TOPIC 2. COMMENTING YOUR SCRIPTS IN PHP

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.

Syntax for Single-Line Comments

In PHP, there are two ways to write a single-line comment:

1. Using //:

// This is a single-line comment

$x = 5; // This comment explains the variable $x

2. Using #:

# This is another way to write a single-line comment

$y = 10; # This comment explains the variable $y

When to Use Single-Line Comments

 To explain a single line of code:

$total = $price * $quantity; // Calculate the total cost

 To temporarily disable a line of code:

// echo "This line is commented out and won't execute";

 To provide brief notes or reminders:

// TODO: Add error handling here

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:

Multi-line comment as an explanation:

/*

The next statement will print a welcome message

*/

echo "Welcome Home!";


Example

Multi-line comment to ignore code:

/*

echo "Welcome to my home!";

echo "Mi casa su casa!";

*/

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.

SUB-TOPIC 3. VARIABLES AND DATA TYPES

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.

Rules for PHP variables:

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

iii. A variable name cannot start with a number

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:

$name = "John Doe"; // String

$age = 30; // Integer

$is_student = true; // Boolean

Output Variables

The PHP echo statement is often used to output data to the screen.

Example shows how to output text and a variable:

$txt = "W3Schools.com";

echo "I love $txt!";

Example shows how to produce the same output as the example above:

$txt = "W3Schools.com";

echo "I love " . $txt . "!";


Example will output the sum of two variables:

$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.

Common Data Types in PHP:

i. String: A sequence of characters, e.g., "Hello, World!".

$greeting = "Hello, World!";

Integer: A whole number, e.g., 42.

$age = 25;

ii. Float (Double): A number with a decimal point, e.g., 3.14.

$price = 19.99;

iii. Boolean: Represents two possible states: true or false.

$is_student = true;

iv. Array: A collection of values stored in a single variable.

$colors = array("red", "green", "blue");

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:

define("SITE_NAME", "My Website");

echo SITE_NAME;

Explanation:

 define() is used to define a constant.

 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.

Create a PHP Constant

To create a constant, use the define() function.

Syntax

define (name, value, case-insensitive);

Example: Create a constant with a case-sensitive name:

define("GREETING", "Welcome to W3Schools.com!");

echo GREETING;

Example: Create a constant with a case-insensitive name:

define ("GREETING", "Welcome to W3Schools.com!", true);

echo greeting;

SUB-TOPIC 5. Operators

Operators in PHP are used to perform operations on variables and values.

Types of Operators:

Arithmetic Operators: Used for mathematical calculations.

$sum = 5 + 10; // Addition

$diff = 10 - 5; // Subtraction

$prod = 5 * 10; // Multiplication

$quot = 10 / 2; // Division

$mod = 10 % 3; // Modulus (remainder)

Assignment Operators: Used to assign values to variables.

php

Copy code

$x = 10; // Assigns 10 to $x

$x += 5; // Adds 5 to $x (same as $x = $x + 5)

Comparison Operators: Used to compare two values.

php

Copy code

$x == $y; // Equal to

$x != $y; // Not equal to


$x < $y; // Less than,,

$x > $y; // Greater than

Logical Operators: Used to combine conditional statements.

php

Copy code

$x && $y; // And

$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`.

if Statement: It executes code if a condition is true.

<?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.

while Loop: It repeats a block of code as long as a condition is true.


Syntax:
while (condition) {
// code to be executed
}

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.

foreach Loop: It loops through each item in an array.

<?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");

PHP Array Types


In PHP, there are three types of arrays
1. Indexed arrays - Arrays with a numeric index
2. Associative arrays - Arrays with named keys
3. Multidimensional arrays - Arrays containing one or more arrays

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);

Accessing Indexed Arrays


To access an array item you can refer to the index number.
$cars=array("Volvo","BMW","Toyota");
echo$cars[0];

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);

2. PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.
$car=array("brand"=>"Ford","model"=>"Mustang","year"=>1964);
var_dump($car);

Accessing Associative Arrays


To access an array item you can refer to the key name.
$car=array("brand"=>"Ford","model"=>"Mustang","year"=>1964);
echo$car["model"];

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);

PHP Create Arrays


Create Array
You can create arrays by using the array() function:
Example
$cars=array("Volvo","BMW","Toyota");

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
];

3. PHP Multidimensional Arrays


PHP - Multidimensional Arrays: A multidimensional array is an array containing one or more
arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";


echo $cars[1][0].": In stock: ".$cars[1][1]."v, sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

for ($row = 0; $row < 4; $row++) {


echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}

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

NB: A function will be executed only when we call them.


<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>Page Title</title>

</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.

How to Call Functions in PHP


To call a function, first make sure the function is defined in your PHP code. Functions are defined before they are
called, either in the same file or in an included file.
Then, add the function name followed by parentheses () that may contain any required arguments.
For example, the greet() function doesn't require any arguments, so you can call it like this:

<?php

greet();

?>

PHP Function Arguments

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

$result = sum(3, 5);

?>

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) {

echo "Hello, " . $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.

How to Create User-Defined Functions in PHP


A user-defined function is a function that is created by a programmer to perform a specific set of tasks or
calculations. Unlike built-in functions, which are provided by the programming language or libraries, user-defined
functions are customized to suit their specific needs.
To create a user-defined function, start by adding the function keyword, followed by the desired name for your
function.
Choose a meaningful and descriptive name that reflects the purpose of the function. For example, let's create a
function called calculateSum():
<?php
function calculateSum() {
// Function body goes here
}
?>
If your function requires input from a user, you can define parameters within the parentheses after the function
name. Parameters act as placeholders for values that are passed into the function when it’s called.
For instance, let’s have our calculateSum() function calculate the sum of two numbers:
<?php
function calculateSum($num1, $num2) {
$sum = $num1 + $num2;
echo "The sum is: " . $sum;
}
?>
To use the user-defined function, simply call it by its name followed by parentheses, providing any required
arguments, like so:
<?php
calculateSum(3, 5);
?>
Exercise
1. Define functions for
2. Implement 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";
}

echo "Result: " . $result;


}
?>
</body>
</html>

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.

Start a PHP Session


A session is started with the session_start() function.

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>

Modify a PHP Session Variable


To change a session variable, just overwrite it:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session


To remove all global session variables and destroy the session, use session_unset() and session_destroy():

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</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.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie


The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30
days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you
prefer).

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).

Modify a Cookie Value


To modify a cookie, just set (again) the cookie using the setcookie() function:

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>

Check if Cookies are Enabled


The following example creates a small script that checks whether cookies are enabled. First, try to create a test
cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>

</body>
</html>

PHP File Handling


File handling is an important part of any web application. You often need to open and process a file for different
tasks.

PHP Manipulating Files


PHP has several functions for creating, reading, uploading, and editing files.

PHP readfile() Function


The readfile() function reads a file and writes it to the output buffer.

Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:

AJAX = Asynchronous JavaScript and XML


CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

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.

PHP Create File - fopen()


The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the
same function used to open files.

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

$myfile = fopen("testfile.txt", "w")

PHP File Permissions


If you are having errors when trying to get this code to run, check that you have granted your PHP file access to
write information to the hard drive.

PHP Write to File - fwrite()


The fwrite() function is used to write to a file.

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

PHP Read File - fread()


The fread() function reads from an open file.

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"));

PHP Close File - fclose()

The fclose() function is used to close an open file.

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);
?>

PHP Read Single Line - fgets()


The fgets() function is used to read a single line from a file.

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);
?>

PHP Read Single Character - fgetc()


The fgetc() function is used to read a single character from a file.

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

You might also like