Chapter Two
Chapter Two
Programming II
Chapter Two
By : Dawit Yetmgeta
Chapter Two
Basic PHP Syntax - Escaping to PHP
There are four ways the PHP parser engine can differentiate PHP code in a
webpage:
1. Canonical PHP Tags: the most popular and effective PHP tag style
2. Short-open Tags: These are the shortest option, but they might need a
bit of configuration, and you might either choose the --enable-shorttags
configuration option when building PHP, or set the short_open_tag setting
in your php.ini file
page 1
Chapter Two
Basic PHP Syntax - Escaping to PHP
3. ASP-like Tags: In order to use ASP-like tags, you’ll need to set the
configuration option in the php.ini file.
4. HTML script Tags: You can define a new script with an attribute language
like so,
page 2
Chapter Two
Commenting In PHP
Single Line Comments
Multi-Line Comments
page 3
Chapter Two
Case Sensitivity
In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while,
echo, etc.) are NOT case-sensitive.
Example:
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
page 4
Chapter Two
A simple Hello World
page 5
Chapter Two
PHP Variables
Variables are "containers" for storing information.
They are Loosly Typed Language
page 6
Chapter Two
PHP Variable Scope
The scope of a variable is the part of the script where the variable can be
referenced/used.
PHP has three different variable scopes:
local: declared within a function and only be accessed within that
function
global: declared outside a function and only be accessed outside a
function
static: a variable is used after a function is completed/executed
Also, you can use a global array to store global variables.
$GLOBALS[index];
page 7
Chapter Two
PHP Variable Scope
Local Global Static
<?php <?php
<?php
$x = 5; function myTest() {
function myTest() {
$y = 10;
$x = 5; // local scope static $x = 0;
echo "<p>Variable x inside echo $x;
function myTest() {
function is: $x</p>"; $x++;
global $x, $y;
} }
$y = $x + $y;
myTest();
}
myTest(); //outputs 0
echo "<p>Variable x outside myTest(); // outputs 1
myTest();
function is: $x</p>"; myTest(); // outputs 2
echo $y; // outputs 15
?> ?>
?>
page 8
Chapter Two
PHP Data Types
1. String: sequence of characters
2. Integer: set of non-decimal numbers
3. Float: a set of numbers with a decimal point
4. Boolean: stores a state of being true or false
5. Array: stores multiple values in one single variable but the same type
6. Object: an instance of a class.
7. NULL: assigns no value except null.
To see the type of the variable use: var_dump($variable name);
To remove the variable use: unset($age);
page 9
Chapter Two
PHP String Functions
1. strlen() - Return the Length of a String
2. str_word_count() - Count Words in a String
3. strrev() - Reverse a String
4. strpos() - Search For a Text Within a String
5. str_replace() - Replace Text Within a String
6. rtrim() - Removes whitespace or other characters from the right side
of a string
Other functions - https://www.w3schools.com/php/php_ref_string.asp
page 10
Chapter Two
PHP Predefined Variables
PHP provides a large number of predefined variables to all scripts. The variables
represent everything from external variables to built-in environment variables,
last error messages to last retrieved headers.
Superglobals — Built-in variables that are always available in all scopes
$GLOBALS — References all variables available in global scope
$_SERVER — Server and execution environment information
$_GET — HTTP GET variables
$_POST — HTTP POST variables
$_FILES — HTTP File Upload variables
$_REQUEST — HTTP Request variables
$_SESSION — Session variables
page 11
Chapter Two
PHP Predefined Variables
$_ENV — Environment variables
$_COOKIE — HTTP Cookies
$php_errormsg — The previous error message
$http_response_header — HTTP response headers
$argc — The number of arguments passed to script
$argv — Array of arguments passed to script
page 12
Chapter Two
PHP Constant Variables
Constants are created using the const statement or the define function.
The convention is to use UPPERCASE letters for constant names.
Constants are automatically global and can be used across the entire script.
page 13
Chapter Two
PHP Constant Variables Cont..
Syntax of constant variable using define function.
define(name, value, case-insensitive)
<?php
define("MESSAGE", "PHP CONSTANTS", true);
echo message;
?>
To get All pre defined constants in php use this function
<?php
$constants = get_defined_constants();
var_dump($constants); // pretty large list
?>
page 14
Chapter Two
Arithmetic and Logical Operators
Arithmetic Operators
page 15
Chapter Two
Arithmetic and Logical Operators Cont..
Assignment Operators
page 16
Chapter Two
Arithmetic and Logical Operators Cont..
Comparison Operators
page 17
Chapter Two
Arithmetic and Logical Operators Cont..
Increment / Decrement Operators
page 18
Chapter Two
Arithmetic and Logical Operators Cont..
Logical Operators
page 19
Chapter Two
Control Structures
Conditional statements are used to execute different code based on
different conditions.
page 20
Chapter Two
if , if else, if .. else .. if , and switch Statement
The if statement executes a piece of code if a condition is true.
If Else Statement
The If. . . Else statement executes a piece of code if a condition is true and
another piece of code if the condition is false.
The If.. else .. if .. statement is used to define what should be executed in the
case when two or more conditions are present.
The switch statement is same as if.. else .. if .. but different syntax.
If Statement If else Statement
if (condition) { if (condition) {
//code to be executed if the condition is true; code to be executed if the condition is true;
// only one condition } else {
} code to be executed if the condition is false; }
page 21
Chapter Two
if , if else, if .. else .. if , and switch Statement Cont.
If ... else ... if Statement Switch Statement
if (condition) { switch (n) {
code to be executed if this condition is case label1:
true; code to be executed if n=label1;
} elseif (condition) { break;
code to be executed if the first condition case label2:
is false and this condition is true; code to be executed if n=label2;
} else { break;
code to be executed if all conditions are default: //code to be executed if n is different from all
false; labels;
} }
page 22
Chapter Two
Loop Statements
In PHP, just like any other programming language, loops are used to execute
the same code block for a specified number of times. Except for the common
loop types (for, while, do. . . while), PHP also support foreach loops.
For Loop
The for loop is used when the programmer knows in advance how many times
the block of code should be executed. This is the most common type of loop
encountered in almost every programming language.
for (initialization; condition; step)
{
// executable code
}
page 23
Chapter Two
Loop Statements
In PHP, just like any other programming language, loops are used to execute
the same code block for a specified number of times. Except for the common
loop types (for, while, do. . . while), PHP also support foreach loops.
For Loop
The for loop is used when the programmer knows in advance how many times
the block of code should be executed. This is the most common type of loop
encountered in almost every programming language.
for (initialization; condition; step)
{
// executable code
}
page 24
Chapter Two
Loop Statements
For each Loop
The foreach loop is used to loop through arrays, using a logic where for each
pass, the array element is considered a value and the array pointer is advanced
by one, so that the next element can be processed.
foreach (array as value)
{
// executable code
}
page 25
Chapter Two
Loop Statements
While Loop
The while loop is used when we want to execute a block of code as long as a
test expression continues to be true.
while (condition)
{
// executable code
}
page 26
Chapter Two
Arrays
Arrays are used to store multiple values which have the same type in a single
variable.
page 27
Chapter Two
Arrays
Initializing an Array
An array can be initialized empty: An array can also be initialized with custom
indexes (also called an Associative array):
page 28
Chapter Two
Arrays
Looping through Indexed array Looping through Associative array
<?php <?php
$fruit = array("apples", "pears", "oranges"); $fruit=array("f1"=>"apples","f2"=>"pears","3"=>"oranges");
$len = count($fruit);
page 29
Chapter Two
Multi Dimensional Arrays
In PHP, a multidimensional array is an array that contains other arrays as its
elements.
It allows you to store and manipulate structured data in a hierarchical manner.
Multidimensional arrays can have two or more dimensions, such as rows and
columns.
page 30
Chapter Two
Multi Dimensional Arrays
Two-dimensional array Accessing Tow Dimensional array
$matrix = array( // Two-dimensional array
array(1, 2, 3), echo $matrix[1][2]; // Output: 6
array(4, 5, 6),
array(7, 8, 9) // Associative multidimensional array
); echo $employees[0]["name"]; // Output: John
Modifying Multidimensional Array Elements
Associative multidimensional array
// Two-dimensional array
$employees = array(
$matrix[0][1] = 10;
array("name" => "John", "age" => 30),
array("name" => "Jane", "age" => 25),
// Associative multidimensional array
array("name" => "Mike", "age" => 35)
$employees[1]["age"] = 26;
);
page 31
Chapter Two
Multi Dimensional Arrays
Looping Through Multidimensional Arrays
page 32
Chapter Two
Array Functions
PHP provides a wide range of built-in functions for working with arrays:
Sorting functions
sort(): Sorts a numeric array in ascending order.
rsort(): Sorts a numeric array in descending order.
asort(): Sorts an associative array in ascending order by value.
arsort(): Sorts an associative array in descending order by value.
ksort(): Sorts an associative array in ascending order by key.
krsort(): Sorts an associative array in descending order by key.
page 33
Chapter Two
Array Functions cont..
Filtering Functions
array_filter(): Filters the elements of an array based on a callback
function.
array_map(): Applies a callback function to each element of an array and
returns a new array.
Transformation Functions
array_reverse(): Reverses the order of elements in an array.
array_unique(): Removes duplicate values from an array.
array_merge(): Merges two or more arrays into a single array.
page 34
Chapter Two
Array Functions cont..
Other Functions
count(): Returns the number of elements in an array.
array_keys(): Returns an array of keys from an associative array.
array_values(): Returns an array of values from an associative array.
array_slice(): Returns a portion of an array based on the given offset and
length.
page 35
Chapter Two
PHP Superglobal Variables
Superglobal variables in PHP are
predefined variables that are
accessible from any scope within
a PHP script.
They provide information about
the server, client, and other
runtime environments.
Superglobals are prefixed with a
special character "$" and are
available in all scopes.
page 36
Chapter Two
$_SERVER
$_SERVER is a PHP superglobal variable that contains server and execution
environment information.
It provides details such as request headers, server information, and script
locations.
Example:
echo $_SERVER['SERVER_NAME']; // Output: example.com
echo $_SERVER['REQUEST_METHOD']; // Output: GET
page 37
Chapter Two
Elements of $_SERVER
$_SERVER['SERVER_NAME']: The name of the server host.
$_SERVER['REQUEST_METHOD']: The HTTP request method used to access the page.
$_SERVER['SCRIPT_FILENAME']: The absolute path of the currently executing script.
$_SERVER['SCRIPT_FILENAME']: The absolute path of the currently executing script.
$_SERVER['REMOTE_ADDR']: The IP address of the client making the request.
$_SERVER['HTTP_USER_AGENT']: The user agent string of the client's browser.
Example:
echo $_SERVER['SERVER_NAME']; // Output: localhost
echo $_SERVER['REQUEST_METHOD']; // Output: GET
echo $_SERVER['SCRIPT_FILENAME']; // Output: /var/www/html/index.php
echo $_SERVER['SERVER_SOFTWARE']; // Output: Apache/2.4.41 (Ubuntu)
echo $_SERVER['REMOTE_ADDR']; // Output: 127.0.0.1
echo $_SERVER['HTTP_USER_AGENT']; // Output: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36
page 38
Chapter Two
$_GET and $_POST
$_GET and $_POST are PHP superglobal variables used to retrieve data from
HTTP requests.
They are commonly used to handle form submissions and query parameters.
$_GET
$_GET is an associative array that contains the values sent through the URL
query parameters.
It is suitable for retrieving data from the server using the HTTP GET method.
Example: // URL: example.com?name=John&age=25
echo $_GET['name']; // Output: John
echo $_GET['age']; // Output: 25
page 39
Chapter Two
$_GET and $_POST
$_POST
$_POST is an associative array that contains the values sent through an HTTP
POST request.
It is suitable for sending sensitive or large amounts of data.
Example: HTML form:
<form method="post" action="process.php">
<input type="text" name="username">
<input type="password" name="password">
</form>
echo $_POST['username']; // Output: JohnDoe
echo $_POST['password']; // Output: ********
page 40
Chapter Two
Handling Form Submissions
When a form is submitted, you can access the form data using $_POST.
Example: Handling a login form submission.
page 41
Chapter Two
$_SESSION
$_SESSION is a PHP superglobal variable used to store session data.
It allows you to store and access data across multiple pages or requests.
Example:
// Start the session
session_start();
page 44
Chapter Two
Retrieving Setting and Deleting Cookie Values
Retrieving Cookie Values
Use $_COOKIE to retrieve the value of a cookie set by the client.
echo $_COOKIE['language']; // Output: en-US
Setting a Cookie
Use setcookie() to set a cookie with a name, value, expiration time, path, and other
optional parameters.
setcookie('language', 'en-US', time() + (86400 * 30), '/');
Deleting a Cookie
To delete a cookie, set its expiration time to a past value using setcookie().
setcookie('language', '', time() - 3600, '/');
page 45
Chapter Two
$_FILES
$_FILES is a PHP superglobal variable used to retrieve uploaded file
information.
It is used to handle file uploads through HTML forms.
Example:
// HTML form: <form method="post" enctype="multipart/form-data">
<input type="file" name="file">
</form>
// Access uploaded file information
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
// Move the uploaded file to a new location
move_uploaded_file($file_tmp_name, 'uploads/' . $file_name);
page 46
Chapter Two
Handling and moving File uploads
Handling File Uploads Moving Uploaded Files Use
When a file is uploaded, you can access its move_uploaded_file() to move an
information using $_FILES. uploaded file to a new location.
Example: Handling a file upload form submission.
if ($_SERVER['REQUEST_METHOD'] === 'POST') { move_uploaded_file($file_tmp_name,
$file_name = $_FILES['file']['name']; 'uploads/' . $file_name); }
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
fclose($file);
page 50
Chapter Two
File Input-Output Cont..
Appending to a File Reading the Entire File
Use fopen() to open a file for Use file_get_contents() to read the entire
appending. contents of a file.
Use fwrite() to append data to the
file. $content = file_get_contents("sample.txt");
$file = fopen("output.txt", "a"); echo $content;
$txt = "Hello again!";
fwrite($file, $txt);
fclose($file);
page 51
Chapter Two
Form Processing
Basic Form Handling
Use the $_POST superglobal to access form data submitted via HTTP POST
method.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
// Process form data
}
page 52
Chapter Two
Form Processing Cont..
Form Validation
Validate form data to ensure it meets certain requirements.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
if (empty($name)) {
$nameError = "Name is required";
}
if (empty($email)) {
$emailError = "Email is required";
}
// Process form data if validation passes
}
page 53
Chapter Two
Form Processing Cont..
Form Sanitization
Sanitize form data to remove unwanted characters and prevent security
vulnerabilities.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
page 54
Chapter Two
Form Processing Cont..
Form Redirects
Redirect users to another page after form processing is complete.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Process form data
header("Location: success.php");
exit;
}
page 55
Chapter Two
Require and include Files
require and include are two of the most commonly used functions in PHP
for including external files.
They allow you to reuse code and break down large applications into
smaller, more manageable files.
Include
The include() function includes the specified file in the current PHP script.
If the file is not found, a warning is issued, but the script continues to run.
Example:
include 'header.php';
page 56
Chapter Two
Require and include Files
Require
The require() function works the same as include(), but if the specified file is not
found, a fatal error is issued, and the script stops running.
Example:
require 'config.php';
Include_once and Require_once
The _once versions of include() and require() ensure that the specified file is
only included once, even if it appears multiple times in the script.
This prevents errors due to redefinition of functions or variables.
Example: include_once 'header.php'; require_once 'config.php';
page 57
Chapter Two
Date and Time
Timestamps
A timestamp is a numeric value that represents the number of seconds between a
specific date and time and the Unix Epoch (January 1, 1970, 00:00:00 UTC).
PHP's time() function returns the current timestamp.
Example: $timestamp = time(); // Get current timestamp
page 59
Chapter Two
Date and Time
Timezones
PHP supports different timezones, allowing you to work with dates and times
based on specific regions.
You can set the timezone using the date_default_timezone_set() function or the
DateTime class.
Example
date_default_timezone_set('America/New_York'); // Set the timezone to New York
page 60
Chapter Two
Date and Time
Time Calculations
String to time, add date, modify, and make time
page 61
Chapter Two
Object Oriented Programming
Definition: OOP is a programming paradigm that organizes code around
objects, which are instances of classes.
Objects: Represent real-world entities or concepts, possessing both data
(properties) and behavior (methods).
Classes:
Definition: Classes are blueprints or templates for creating objects.
Encapsulate data and behavior related to a specific entity or concept.
Objects:
Definition: Objects are instances of classes, created using the new keyword.
Represent specific occurrences or instances of a class.
page 62
Chapter Two
Object Oriented Programming cont..
Benefits of OOP
page 63
Chapter Two
Object Oriented Programming cont..
Principles of OOP
Inheritance: Classes can inherit properties and methods from parent classes.
Supports code reuse and promotes hierarchical relationships between classes.
Polymorphism: Objects can take multiple forms and be used interchangeably.
Achieved through interfaces and abstract classes, allowing for flexible and
extensible code.
Encapsulation: Hiding internal implementation details of a class from the
outside world. Protects data integrity and promotes modular design.
page 64
Chapter Two
Object Oriented Programming cont..
Using Object-oriented Programming
Creating Classes and Objects:
Define classes using the class keyword and create objects using the new
keyword.
Defining Properties and Methods:
Properties store data related to objects, while methods define their
behavior.
Accessing Properties and Methods:
Use object notation ($object->property) to access properties and call
methods.
page 65
Chapter Two
Object Oriented Programming cont..
Creating a Class Properties and Methods
Syntax: class ClassName { ... } Properties: Variables within a class, storing data.
class Car {
class Car { public $color;
// Class definition public $model;
} }
Creating Objects Methods: Functions within a class, performing
Syntax: $objectName = new actions.
ClassName(); class Car {
public function start() {
// Method implementation
$myCar = new Car();
}
}
page 66
Chapter Two
Object Oriented Programming cont..
Accessing Properties and Methods this Keyword
Syntax: It refers to the current
Accessing Properties: $objectName->propertyName instance of the class.
Accessing Methods: $objectName->methodName()
Used to access properties
}
and methods within the class.
Example:
class Car {
$myCar = new Car();
public $color;
$myCar->color = "Red";
$myCar->start(); public function setColor($color) {
$this->color = $color;
}
}
page 67
Chapter Two
Object Oriented Programming cont..
instance of Operator
It checks if an object belongs to a specific
class or its parent classes.
Returns true or false.
Example:
$myCar = new Car();
if ($myCar instanceof Car) {
echo "This is a Car object.";
}
page 68
Chapter Two
Object Oriented Programming cont..
Constructors and Destructors in PHP Example:
class Car {
Constructors
public $color;
Special methods are called when an
object is created.
public function __construct($color) {
Used to initialize object properties.
$this->color = $color;
Syntax: function __construct() { ... }
}
}
page 71
Chapter Two
Object Oriented Programming cont..
Inheritance class Car extends Vehicle {
private $model;
Example:
class Vehicle {
public function __construct($brand, $model) {
protected $brand;
parent::__construct($brand);
$this->model = $model;
public function __construct($brand) { }
$this->brand = $brand; public function getInfo() {
} return parent::getInfo() . " It is a {$this->model}
model.";
public function getInfo() { }
return "This is a {$this->brand} vehicle."; }
} $car = new Car("Toyota", "Camry");
} echo $car->getInfo();
page 72
Chapter Two
Object Oriented Programming cont..
Encapsulation Example
Encapsulation is the practice of class Circle {
bundling data and behavior within a public $radius; // Public property
class, hiding the internal details from private $color; // Private property
the outside world. protected $area; // Protected property
It helps to achieve data abstraction
and protects the integrity of the data. public function calculateArea() {
Access modifiers (public, private, // Calculate area using radius
protected) control the visibility and }
}
accessibility of class members.
page 73
Chapter Two
Object Oriented Programming cont..
Benefits of Encapsulation
Data hiding: Internal implementation details are hidden, preventing direct
access and modification.
Code organization: Encapsulation helps to organize code into logical units
(classes) with clear boundaries.
Code maintainability: Changes to the internal implementation of a class
can be made without affecting other parts of the code.
page 74
Chapter Two
Object Oriented Programming cont..
Access Modifiers:
They are keywords in PHP that control the visibility and accessibility of class
properties and methods. They determine which parts of your code can interact with
these elements.
PHP has four main types of access modifiers:
1. Public: The property or method can be accessed from anywhere, both inside and
outside the class.
2. Protected: The property or method can only be accessed within the class and its
subclasses.
3. Private: The property or method can only be accessed within the class that
defines it.
4. No Modifier (Default): The property or method is accessible within the class and
can be accessed within the same package (namespace), but not outside of it.
page 75
Chapter Two
Object Oriented Programming cont..
Polymorphism
Polymorphism allows objects of different classes to be treated as objects
of a common superclass.
It enables code to be written in a generic way, working with objects based
on their common interface.
Benefits
Code reusability: Polymorphism allows you to write reusable code that can
work with different types of objects.
Flexibility: Objects can be easily substituted with different
implementations without affecting the code that uses them.
Extensibility: New classes can be added without modifying existing code
that relies on the common interface.
page 76
Chapter Two
Object Oriented Programming cont..
Polymorphism
Example function printArea(Shape $shape) {
class Circle implements Shape { echo "Area: " . $shape->calculateArea();
public function calculateArea() { }
// Calculate area for a circle
} $circle = new Circle();
} $rectangle = new Rectangle();
page 78
Chapter Two
Object Oriented Programming cont..
Abstract Classes cont...
Abstract classes are useful when you want to provide a common interface
for a group of related classes.
They can define common methods or properties that child classes can
inherit and implement.
Abstract classes cannot be instantiated directly, but they can be used as
type hints or references. class Dog extends Animal {
Example
public function makeSound() {
abstract class Animal {
echo "Woof!";
abstract public function makeSound();
}
}
}
page 79
Chapter Two
Object Oriented Programming cont..
Interfaces
An interface is a contract between two objects, defining how they will
interact with each other.
In PHP, an interface is a collection of abstract methods that define the
signature of a class.
Interfaces are useful when you want to define a common set of methods
that multiple classes can implement.
They promote code reusability and provide a structured approach to
object-oriented programming.
Interfaces can be used as type hints or references.
page 80
Chapter Two
Object Oriented Programming cont..
Interfaces
Implementing
Defining
class FileLogger implements
interface LoggerInterface {
LoggerInterface {
public function log(string $message);
public function log(string $message) {
}
// Log message to file
}
}
Inheritance
interface DatabaseLoggerInterface extends LoggerInterface {
public function connect();
}
page 81
Chapter Two
Object Oriented Programming cont..
Static Method and Properties
In PHP, the static keyword is used to define properties and methods that
belong to the class itself, rather than an instance of the class.
Static properties and methods are associated with the class itself.
Static members can be accessed without creating an instance of the class.
Use Cases for Static
Creating utility classes with helper methods that don't require object state.
Counting instances of a class using a static property.
Implementing singleton patterns using a static instance.
page 82
Chapter Two
Object Oriented Programming cont..
Static Method and Properties
Properties: Methods
class Counter { class MathUtils {
public static $count = 0; public static function square(int $number): int {
} return $number * $number;
}
Counter::$count = 10; }
$result = MathUtils::square(5);
page 83
Chapter Two
page 83