0% found this document useful (0 votes)
20 views67 pages

Term1 PHP Programming

its from Rwandan school management
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views67 pages

Term1 PHP Programming

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

LO1: APPLY PHP FUNDAMENTALS

1. Preparation of PHP Programming environment


1.1 Definition of key terms
➢ PHP:
PHP stands for Hypertext Pre-processor, that earlier stood for
Personal Home Pages.
➢ Interpreter
What is compiler and interpreter?
Compiler: A compiler translates code from a high-level programming language (like Python, JavaScript or Go)
into machine code before the program runs. Interpreter: An interpreter translates code written in a high-level
programming language into machine code line-by-line as the code runs
➢ Open Source: PHP is freely download from internet
➢ Web Server: On the hardware side, a web server is a computer that stores web server software and a
website's component files (for example, HTML documents, images, CSS stylesheets, and JavaScript
files). A web server connects to the Internet and supports physical data interchange with other devices
connected to the web
➢ Apache; The Apache HTTP Server is a free and open-source cross-platform web server software,
➢ Database: A database is an organized collection of structured information, or data, typically stored
electronically in a computer system
➢ DBMS: What is DBMS? Database Management Systems (DBMS) are software systems used to store,
retrieve, and run queries on data. A DBMS serves as an interface between an end-user and a database,
allowing users to create, read, update, and delete data in the database.
➢ MySQL: MySQL is a relational database management system based on SQL – Structured Query
Language.
➢ Static website: websites have stable content, where every user sees the exact same thing on each
individual page (like a privacy policy)
➢ Dynamic website: dynamic websites pull content on-the-fly, allowing its content to change with the
user
1.2 Purpose of PHP
PHP is a server-side scripting language embedded in HTML in its simplest form. PHP allows web developers
to create dynamic content and interact with databases
1.3 Important characteristics of PHP
It's Open-source: Meaning free to use.
It is adaptable: It works different operating system such as Windows, Linux, or Mac OS. It also supports
almost all web servers such as Apache HTTP Server, Microsoft Internet Information Services (IIS), Nginx,
Lighttpd, Sun Java System Web Server.
Excellent database connectivity: PHP most likely has the ability to connect to any database that exists. For
instance- Access, Firebird, MySQL, Oracle, and iBase are among the most popular ones. One of the most
crucial features and the biggest advantages of PHP language is its interoperability and cross-platform
capabilities.
Support for third-party applications and security: Many of PHP's built-in functions include data encryption
options, making the language safer. Applications from third parties can be used to secure data by users as well.
Monitoring of real-time access: PHP additionally offers a list of users' most recent logging accesses.
Features of object-oriented programming: PHP supports these features, making it faster and adding new
ones like data encapsulation and inheritance at various levels.
Despite several other languages and tools coming and getting extinct, PHP has continued to remain and doing
exceptionally great. The fundamentals involved in PHP remain the same along with a few enhancements in the
language.
1.4 PHP Development Tools
XAMPP/WAMP: The full form of XAMPP is Cross-platform, Apache, Mysql, Php, and Perl. The full form
of WAMP is Windows, Apache, Mysql, and Php. The main difference between xampp and wamp is that
multiple operating systems are supported by xampp, but wamp can only work on Windows operating systems.
MAMP: The name MAMP is an acronym that stems from the names of the components of the system: macOS
(the operating system); Apache (the web server); MySQL or MariaDB (the database management system); and
PHP, Perl, or Python (programming languages used for web development).
LAMP: LAMP is an acronym for the operating system, Linux; the web server, Apache; the database server,
MySQL; and the programming language, PHP. All four of these technologies are open source, which means
they are community maintained and freely available for anyone to use.
IDEs: IDE stands for the integrated development environment (IDE). IDE Provides an Environment
consolidated for the Programmer to write a Computer Program. IDE helps in combining common activities of
writing software into a single application such as editing source code, building executables, and debugging.
(ex: PHPStorm, Netbeans, Eclipse, Zend Studio, Visual Studio Code.)
Text Editors: Text Editor is a free app that allows you to create, open, and edit text files on your computer
(ex: Notepad, Sublime Text, Notepad++, Brackets, SlickEdit, Codelobster, Codeanywhere, UltraEdit)
Browser: A web browser is an application for accessing websites. When a user requests a web page from a
particular website, the browser retrieves its files from a web server and then displays them
1.5 Installation of XAMPP/WAMP or LAMP
XAMPP is a free and open source cross-platform web server solution developed by Apache Friends, consisting
mainly of the Apache HTTP Server, MariaDB database, and interpreters for scripts written in the PHP and Perl
programming languages.
In order to make your PHP code execute locally, first install XAMPP.
• Download XAMPP
• Install the program (check the technologies you want during installation)
1.6 Configuration of environment
Open XAMPP and click on "Start" on Apache and MySQL (when working with databases)
Place your web project inside the htdocs directory. In the common case, if you installed XAMPP directly
inside the C: drive of your PC, the path to this folder would be: C:xampp/htdocs in case of WAMP the path
is C:wamp/www
To test the services are up and running you can just enter localhost in your address bar and expect the
welcoming page.
1.7 Application of PHP concepts
1. PHP file extension
A PHP file contains PHP tags and ends with the extension ".php".Older PHP file extensions include
• .phtml
• .php3
•. php4
•. php5
•. phps
2. PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the browser
A PHP script starts with < ? php and ends with ?>
<?php
PHP code goes here
?>
Note: PHP statements end with a semicolon (;).

3. Data types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
Note: Since PHP 5.4+ you can also specify integers in binary (base 2) notation. To use binary notation, precede
the number with 0b (e.g. $var = 0b11111111;).
In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
Example
<?php
$x= 5985;
var_dump($x);
?>
PHP String
Strings are sequences of characters, where every character is the same as a byte. A string can hold letters,
numbers, and special characters and it can be as large as up to 2GB (2147483647 bytes maximum). The simplest
way to specify a string is to enclose it in single quotes (e.g. 'Hello world!'), however you can also use double
quotes ("Hello world!")

Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Float
A float (also known as floating point number, doubles or real numbers) is a number with a decimal point or a
number in exponential form.
Example
<?php
$x= 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.
Example:
<?php
$x = true;
var_dump($x);
$y = false;
var_dump($y);
?>
PHP Array
An array is a variable that can hold more than one value at a time. It is useful to aggregate a series of related
items together, for example a set of country or city names. An array is formally defined as an indexed collection
of data values. Each index (also known as the key) of an array is unique and references a corresponding value.
We will learn a lot more about arrays in later chapters
In the following example $cars is an array

<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

PHP Object
Classes and objects are the two main aspects of object-oriented programming.
An object is a data type that not only allows storing data but also information on, how to process that data.
A class is a template for objects, and an object is an instance of a class.
First we must declare a class of object. For this, we use the class keyword.
Objects are created based on this template via the new keyword.
Every object has properties and methods corresponding to those of its parent class. Every object instance is
completely independent, with its own properties and methods, and can thus be manipulated independently of
other objects of the same class. Here's a simple example of a class definition followed by the object creation
<?php
// Class definition
class greeting{
// properties
public $str = "Hello World!";
// methods
function show_greeting(){
return $this->str;
}
}
// Create object from class
$message = new greeting;
var_dump($message);
?>
Note: The data elements stored within an object are referred to as its properties and the information, or code
which describing how to process the data is called the methods of the object

PHP NULL

The special NULL value is used to represent empty variables in PHP. A variable of type NULL is a variable
without any data.

Note: If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL


Example
<?php
$a = NULL;
var_dump($a);
echo "<br>";
$b = "Hello World!";
$b = NULL;
$b;
var_dump($b);
var_dump($b);
?>
Note: Many novice PHP developers mistakenly considered both $var1 = NULL; and $var2 = ""; are same, but
this is not true. Both variables are different — the $var1 has null value while $var2 indicates no value assigned
to it.
PHP Resource
The special resource type is not an actual data type. It is variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database connections. We will see in
next chapters
4. PHP Variables
Variables are "containers" for storing information.
Creating (Declaring) PHP Variables.
In PHP, a variable starts with the $ sign, followed by the name of the variable. A variable can have a short
name (like x and y) or a more descriptive name (age, carname, total_volume).

Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
$tvet_school="Gahanga TSS";
?>
Note: 1. When you assign a text value to a variable, put quotes around the value.
2. Unlike other programming languages, PHP has no command for declaring a variable. It is created
the moment you first assign a value to it.
Rules for PHP variables:
➢ A variable start with the $ sign, followed by the name of the variable
➢ A variable name must start with a letter or the underscore character
➢ A variable name cannot start with a number
➢ A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
➢ Variable names are case-sensitive ($age and $AGE are two different variables)
➢ Output Variables The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<?php
$txt = "PHP Programming"; echo "I love $txt Teacher";
?>
The following example will output the sum of two variables:
Example
<?php
$x = 5; $y = 4;
echo $x + $y;
?>
Note: PHP is a Loosely Typed Language. In the example above, notice that we did not have to tell PHP which
data type the variable is. PHP automatically converts the variable to the correct data type, depending on its
value.

5. PHP Variables Scope


In PHP, variables can be declared anywhere in the script. 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
• Global
• Static
Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
You can have local variables with the same name in different functions, because local variables are only
recognized by the function in which they are declared.
PHP The global Keyword
The global keyword is used to access a global variable from within a function. To do this, use the global
keyword before the variables (inside the function): Example

<?php
$x = 5;
$y = 10;
function yTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the
variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want
a local variable NOT to be deleted. We need it for a further job. To do this, use the static keyword when you
first declare the variable: Example
<?php
function myTest() {
static $x = 0;
$x++;
echo $x;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained from the last
time the function was called.
Note: The variable is still local to the function.

6.PHP Constants

Constants are like variables except that once they are defined they cannot be changed or undefined. 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).
Note: Unlike variables, constants are automatically global across the entire script. To create a PHP constant,
use the define() function.
Syntax: define(name, value, case- insensitive)
- Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false The
example below creates a constant with a case-sensitive name: Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
The example below creates a constant with a case-insensitive name:
<?php
define("GREETING", "Welcome to W3Schools.com!",true);
echo greeting;
?>
Constants are Global
Constants are automatically global and can be used across the entire script. The example below uses a constant
inside a function, even if it is defined outside the function: Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
function
myTest() {
echo
GREETING;
}
myTest();
?>
7.PHP Operators
Operators are used to perform operations on variables and values. PHP divides the operators in the following
groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
8. Conditional Operator

1. Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such
as addition, subtraction, multiplication, division, modulus and Exponentiation.
2. Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment
operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the
right.
x = y here the left operand(x) gets set to the value of y
You can also write:
x += y equals to x = x + y Addition
x -= y equals to x = x - y Subtraction
x *= y equals to x = x * y Multiplication
x /= y equals to x = x / y Division
x % y Modulus
3. Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x===$y Returns true if $x is equal to $y, and they are of the same
type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x!== $y Returns true if $x is not equal to $y, or they are not of the
same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal $x >= $y Returns true if $x is greater than or equal to $y
to
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y

<=> Spaceship $x<=>$y Returns an integer less than, equal to, or greater than zero,
depending on if $x is less than, equal to, or greater than $y.
Introduced in PHP 7.
4. Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used
to decrement a variable's value.
5. Logical Operators
The PHP logical operators are used to combine conditional statements.

6. String Operators
PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and
$txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1
assignment

7. Array Operators

The PHP array operators are used to compare arrays.


8. Conditional /ternary Operator
The ternary operator is used to set a value depending on conditions
Operator Name Example Result
?: Ternary $x= expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
The value of $x is expr1 if expr1 exists,
and is not NULL.
If expr1 does not exist, or is NULL, the
value of $x is expr2.
Introduced in PHP 7

Example:
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otheriwse b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otheriwse b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>
This will produce the following result:
TEST1 : Value of result is 20
TEST2 : Value of result is 10

The ternary operator allows us to simplify some PHP conditional statements. Let see how it can be used, with
test-driven development and refactoring, to simplify code like:
<?php
$result = null;
if (5>31) {
echo "Bigger";
}
else {
echo"Less";
}
Written using a ternary operator, we can write the above comparison as:
<?php
$result = 5 > 3 ? "Bigger" : "Less";
echo $result;
8.PHP Comments
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is to be read by
someone who is looking at the code.
Comments can be used to:
• Let others understand your code
• Remind yourself of what you did (Most programmers have experienced coming back to their own work
a year or two later and having to re-figure out what they did. Comments can remind you of what you
were thinking when you wrote the code)

Syntax for comments in PHP code:

// This is a single-line comment


# This is also a single-line comment
/* This is a multi-line comment */

Single Line Comments:

Single line comments start with //.


Any text between // and the end of the line will be ignored (will not be executed).
You can also use # for single line comments,

Multi-line Comments:
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.

Comments in the Middle of the Code


The multi-line comment syntax can also be used to prevent execution of parts inside a code-line:
Example
The + 15 part will be ignored in the calculation:
$x = 5 /* + 15 */ + 5;
echo $x;
9. PHP Date and Time
The PHP date() function is used to format a date and/or a time.
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format, timestamp)

Parameter Description

format Required. Specifies the format of the timestamp

timestamp Optional. Specifies a timestamp. Default is the current date and


time
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
• d - Represents the day of the month (01 to 31)
• m - Represents a month (01 to 12)
• Y - Represents a year (in four digits)
• l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional formatting.
The example below formats today's date in three different ways:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Use the date() function to automatically update the copyright year on your website:
Example
&copy; <?php echo date("Y");?>
Get a Time
Here are some characters that are commonly used for times:
• H - 24-hour format of an hour (00 to 23)
• h - 12-hour format of an hour with leading zeros (01 to 12)
• i - Minutes with leading zeros (00 to 59)
• s - Seconds with leading zeros (00 to 59)
• a - Lowercase Ante meridiem and Post meridiem (am or pm)
The example below outputs the current time in the specified format:
Example
<?php
echo "The time is " . date("h:i:sa");
?>
Note that the PHP date() function will return the current date/time of the server!
Get Your Time Zone
If the time you got back from the code is not correct, it's probably because your server is in another country
or set up for a different time zone.
So, if you need the time to be correct according to a specific location, you can set the time zone you want to
use.
The example below sets the time zone to "America/New_York", then outputs the current time in the specified
format:
Example
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
Create a Date With mktime()
The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date
and time will be used (as in the examples above).
Syntax
mktime(hour, minute, second, month, day, year)
The example below creates a date and time with the date() function from a number of parameters in
the mktime() function:
Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
Create a Date From a String With strtotime()
The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp (the
number of seconds since January 1 1970 00:00:00 GMT).
Syntax
strtotime(time, now)
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
PHP is quite clever about converting a string to a date, so you can put in various values:
Example
<?php
$d=strtotime("now");
echo date("Y-m-d h:i:sa", $d);
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
Other examples:
The example below outputs the dates for the next six Saturdays:
<?php
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks", $startdate);
while ($startdate < $enddate) {
echo date("M d", $startdate) . "<br>";
$startdate = strtotime("+1 week", $startdate);
}
?>
The example below outputs the number of days until 1st of February 2024:
<?php
$d1=strtotime("February 01 2024");
$d2=ceil(($d1-time())/60/60/24);
echo "There are " . $d2 ." days until 1st of February 2024.";
?>
10. String Concatenation
To concatenate, or combine, two strings you can use the . operator:
Example
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
The result of the example above is HelloWorld, without a space between the two words.
You can add a space character like this:
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
An easier and better way is by using the power of double quotes.
By surrounding the two variables in double quotes with a white space between them, the white space will
also be present in the result:
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
11. Conditional Statements in PHP

Conditional statements are used to execute different code based on different conditions.
The If statement
The if statement executes a piece of code if a condition is true.
The syntax is:
if (condition) {
// code to be executed in case the condition is true
}
Example:
<?php
$age = 18;
if ($age < 20) {
echo "You are a teenager";
}
?>
Because the condition is true, the result would be:
You are a teenager

The If. . . Else statement


The If. . . Else statement executed a piece of code if a condition is true and another piece of code if the
condition is false.
The syntax is:
if (condition) {
// code to be executed in case the condition is true
}
else {
// code to be executed in case the condition is false
}

An example of an If. . . Else statement would be:


<?php
$age = 25;
if ($age < 20) {
echo "You are a teenager";
}
else {
echo "You are an adult";
}
?>

Because the condition is false, the result in this case would be:
You are an adult

The If. . . Elseif. . . Else statement


This kind of statement is used to define what should be executed in the case when two or more conditions are
present. The syntax of this case would be:
if (condition1) {
// code to be executed in case condition1 is true
}
elseif (condition2) {
// code to be executed in case condition2 is true
}
else {
// code to be executed in case all conditions are false
}
Again, a simple example to demonstrate this:
<?php
$age = 3;
if ($age < 10) {
echo "You are a kid";
} elseif ($age < 20) {
echo "You are a teenager";
} else {
echo "You are an adult";
}
?>
The result, as you might expect, would be:

You are a kid


Nested if statement
The nested if statement contains the if block inside another if block
The inner if statement executes only when specified condition in outer if statement is true
Example:
<?php
$a=13;
if ( $a > 10 ) {
echo "above 10";
if ( $a > 20 ) {
echo " and also above 20";
}
else{
echo "but not above 20 ";
}
}
PHP Switch case
Switch case in PHP are control structures that allow the programmer to execute different blocks of code
based on the value of a variable or expression. the switch statement evaluates a single expression and
compares its value to a set of predefined cases. If a match is found, the corresponding block of code is
executed.
The switch case in PHP can also include a default case that is executed if none of the other cases match.
This can be particularly useful for handling unexpected or unknown input.
Syntax:
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
case value3:
// Code to be executed if expression matches value3
break;
// additional cases as needed
default:
// Code to be executed if none of the cases match the expression
break;
}
Example:
<?php
$dayOfWeek = "Wednesday";
switch ($dayOfWeek) {
case "Monday":
echo "Today is Monday";
break;
case "Tuesday":
echo "Today is Tuesday";
break;
case "Wednesday":
echo "Today is Wednesday";
break;
case "Thursday":
echo "Today is Thursday";
break;
case "Friday":
echo "Today is Friday";
break;
default:
echo "It is the weekend!";
break;
}
?>
✓ Each case statement should end with a break statement to prevent execution from continuing into the
next case statement. If a break statement is not included, all subsequent case statements will be
executed, even if they don't match the value of the variable or expression being evaluated.
✓ The default case is optional, but it is recommended to include one to handle situations where none of
the case statements match the variable or expression is evaluated.
✓ The value of the variable or expression being evaluated in the switch statement should be of a
primitive data type, such as integer, string, or Boolean.
✓ The values in each case statement should also be of the same data type as the value of the variable or
expression is evaluated. For example, if the variable being evaluated is a string, the values in each
case statement should also be strings.
Flowchart:
PHP Switch Statement Is Fall-Through
<?php
$num = 2;
switch ($num) {
case 1:
echo "The number is one. ";
case 2:
echo "The number is two. ";
case 3:
echo "The number is three. ";
break;
default:
echo "The number is not one, two, or three. ";
break;
}
?>
In this example, the switch case in php evaluates the variable $num, which has a value of 2. The case
statements for 1 and 2 do not have a break statement, so execution will "fall through" to the next case
statement.
12. Loops in PHP

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 loop, which is not only specific to PHP. Languages like Javascript and C# already use
foreach loop. Let’s have a closer look at how each of the loop types works.
The 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.
Syntax:
for (initialization; condition; step){
// executable code
}
An example where we use the for loop would be:
<?php
for ($i=0; $i < 5; $i++) {
echo "This is loop number $i <br>";
}
?>
The result of this code snippet would be:
This is loop number 0
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4
The 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.
Syntax:
while (condition){
// executable code
}
An example where we use the while loop would be:
<?php
$i=0; // initialization
while ($i < 5) {
echo "This is loop number $i <br>";
$i++; // step
}
?>
The result of this code snippet would be just the same as before:

This is loop number 0


This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4

To have a clearer idea of the flow of these two loops, look at the graphic below:
The do. . . while loop
The do...while loop is used when we want to execute a block of code at least once and then as long as a
test expression is true.
do {
// executable code
}
while (condition);

An example where we use the do. . . while loop would be:


<?php
$i = 0; // initialization do {
$i++; // step
echo "This is loop number $i <br>";
}
while ($i < 5); // condition
?>

This time the first loop number would be 1, because the first echo was executed only after variable
incrementation:
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4
This is loop number 5

Do…. While Flowchart

A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is
must that the program should not contain any other statements after the do-while loop. In this case, it will not
generate any error.
The following example will increment the value of $x at least once. Because the given condition is false.
<?php
$x = 1;
do {
echo "1 is not greater than 10.";
echo "</br>";
$x++;
} while ($x > 10);
echo $x; ?>

Difference between while and do-while loop

While Loop Do-while loop


✓ The while loop is also named as entry ✓ The do-while loop is also named as exit
control loop. control loop.
✓ The body of the loop does not execute ✓ The body of the loop executes at least once,
if the condition is false. even if the condition is false.
✓ Condition checks first, and then block ✓ Block of statements executes first and then
of statements executes. condition checks.
✓ This loop does not use a semicolon to ✓ Do-while loop use semicolon to terminate the
terminate the loop. loop.
PHP foreach loop

The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an
error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements
of an array.
In foreach loop, we don't need to increment the value.

Syntax
foreach ($array as $value) {
//code to be executed
}
There is one more syntax of foreach loop.
Syntax
foreach ($array as $key => $element) {
//code to be executed
}
Flowchart

Example 1:
PHP program to print array elements using foreach loop.
<?php
//declare array
$season = array ("Summer", "Winter", "Autumn", "Rainy");

//access array elements using foreach loop


foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>
Output:
Summer
Winter
Autumn
Rainy
Example 2:
PHP program to print associative array elements using foreach loop.
<?php
//declare array
$employee = array ( "Name" => "Alex", "Email" => "[email protected]", "Age" => 21, "Gender" =>
"Male"
);
//display associative array element through foreach loop
foreach ($employee as $key => $element) {
echo $key . " : " . $element;
echo "</br>";
}
?>
Output:
Name : Alex
Email : [email protected]
Age : 21
Gender : Male

Example 3:
Multi-dimensional array
<?php
//declare multi-dimensional array
$a = array();
$a[0][0] = "Alex";
$a[0][1] = "Bob";
$a[1][0] = "Camila";
$a[1][1] = "Denial";
//display multi-dimensional array elements through foreach loop
foreach ($a as $e1) {
foreach ($e1 as $e2) {
echo "$e2\n";
}
}
?>

Output:
Alex Bob Camila Denial

Example 4:
Dynamic array
<?php
//dynamic array
foreach (array ('P','H','P','','P','R','O','G','R','A','M','M','I','N','G') as $elements) {
echo "$elements\n";
}
?>
Output: PHP PROGRAMMING
Nesting Loops in PHP

Nested loop is a loop within a loop, an inner loop within the body of an outer one.
The inner loop executes only when the outer loop condition is found true.
Nested loop is executed fully for one outer loop.(Ex: If outer loop is to be executed for 3 times and inner
loop for 3 times, inner loop will be executed 9 times (3 tim ifes for 1st outer loop, 3 times for 2nd outer loop
and 3 times for 3rd outer loop).
Normally nested for loop is used. while and do.. while not used.
Syntax:
//nested for
for (expr1; expr2; expr3) {
for (expr1; expr2; expr3) {
//statement;
}
}
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
}
}
?>
Example1:
<?php
for ($i = 1; $i < 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo " * ";
}
echo '<br />';
}
?>
Output:

Example2:
<?php
for ($i = 1; $i < 5; $i++) {
for ($j = $i; $j < 5; $j++) {
echo " * ";
}
echo '<br />';
}
?>
Example3:
<?php
for ($i = 1; $i < 5; $i++) {
for ($j = $i; $j <= 5; $j++) {
echo "&nbsp;"; // it will print blank space
}
for ($j = 1; $j <= $i; $j++) {
echo " * ";
}
echo '<br />';
}
?>

PHP Break statement

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If
you use break inside inner loop, it breaks the execution of inner loop only.
The break keyword immediately ends the execution of the loop or switch structure. It breaks the current flow
of the program at the specified condition and program control resumes at the next statements outside the loop.
The break statement is situated inside the statement block. It gives you full control and whenever you want to
exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be
executed.
Syntax:
jump-statement;
Break;
Flowchart
Example
In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<?php
$i = 0;
while( $i < 10) {
$i++;
echo $i."<br>";
if( $i == 3 )
break;
}
echo ("Loop stopped at i = $i" );
?>
PHP Break: inside inner loop
The PHP break statement breaks the execution of inner loop only.
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
if($i==2 && $j==2){
break;
}
}
}
?>
PHP Break: inside switch statement
The PHP break statement breaks the flow of switch case also.
<?php
$num=200;
switch($num){
case 100:
echo("number is equals to 100");
break;
case 200:
echo("number is equal to 200");
break;
case 50:
echo("number is equal to 300");
break;
default:
echo("number is not equal to 100, 200 or 500");
}
?>
PHP Break: with array of string

<?php
//declare an array of string
$number = array ("One", "Two", "Three", "Stop", "Four");
foreach ($number as $element) {
if ($element == "Stop") {
break;
}
echo "$element </br>";
}
?>

PHP continue statement

The PHP continue statement is used to continue the loop. It continues the current flow of the program and
skips the remaining code at the specified condition.
The continue statement is used within looping and switch control structure when you immediately jump to
the next iteration.
The continue statement can be used with all types of loops such as - for, while, do-while, and foreach loop.
The continue statement allows the user to skip the execution of the code for the specified condition.
Syntax:
jump-statement;
continue;
Flowchart:
PHP Continue Example with for loop

In the following example, we will print only those values of i and j that are same and skip others.
<?php
//outer loop
for ($i =1; $i<=3; $i++) {
//inner loop
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue; //skip when i and j does not have same values
}
echo $i.$j;
echo "</br>";
}
}
?>
PHP continue Example in while loop

In the following example, we will print the even numbers between 1 to 20.
<?php
//php program to demonstrate the use of continue statement

echo "Even numbers between 1 to 20: </br>";


$i = 1;
while ($i<=20) {
if ($i %2 == 1) {
$i++;
continue; //here it will skip rest of statements
}
echo $i;
echo "</br>";
$i++;
}
?>
PHP continue Example with array of string

The following example prints the value of array elements except those for which the specified condition is
true and continue statement is used.
<?php
$number = array ("One", "Two", "Three", "Stop", "Four");
foreach ($number as $element) {
if ($element == "Stop") {
continue;
}
echo "$element </br>";
}
?>
PHP continue Example with optional argument
The continue statement accepts an optional numeric value, which is used accordingly. The numeric value
describes how many nested structures it will exit.

<?php
//outer loop
for ($i =1; $i<=3; $i++) {
//inner loop
for ($j=1; $j<=3; $j++) {
if (($i == $j) ) { //skip when i and j have same values
continue 1; //exit only from inner for loop
}
echo $i.$j;
echo "</br>";
}
}
?>

Continue in Do While Loop


Stop, and jump to the next iteration if $i is 3:
<?php
$i = 0;
do {
$i++;
if ($i == 3)
continue;
echo $i;
}
while ($i < 6);
?>

13. PHP Functions


Functions are reusable bits of code that you use throughout a program. They help to better organize your
Application as well as eliminate the need to copy/paste repetitive pieces of code. In an ideal world an
application should not have multiple functions doing the same thing.
In PHP, we can define Conditional function, Function within Function and Recursive function also.
Advantage of PHP Functions
Code Reusability: PHP functions are defined only once and can be invoked many times, like in other
programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of
function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of
the application because every logic is divided in the form of functions.
PHP has a lot! of built in functions (Thousands built in functions) and while we are not expected to learn all
of them at once there are some useful functions that can help in everyday programming and we will start
from there.

String Manipulation Functions

Some of the most useful PHP functions are string manipulation functions. As the name suggests they
manipulate strings.
➢ Finding the length of a String : The strlen() function works by passing a string or variable and then
returns the total number of characters including spaces.
Example
<?php
$name = "Matthew ";
echo strlen($name); // 8
?>
➢ Return part of a String : The substr() function is used to return a substring or part of a string. This
function has 3 parameters which you can pass along.
Syntax: substr($string, $start,$length);
✓ $string : a string of text or a variable containing a string of text. Input must be at least one character.
✓ $start : think of the string as an array starting from [0]. If you wanted to start from the first character
you would enter 0. A negative value will go to the end of the string.
✓ $length : (Optional) is the number of characters returned after the start character. If this value is less
than or equal to the start value then it will return false.
Example:
<?php
$name = "Matthew ";
echo substr($name, 0, 5)."<br>"; // Matth
echo substr($name, 2)."<br>"; // tthew
echo substr($name, -6, 5); // tthew
?>
Note: If you don’t provide a $length parameter, this function will just return the remainder of the string
starting from the $start parameter.

➢ Converting strings to UPPER or lower case.: Two useful string functions that are simple to use are
strtoupper() and strtolower(), these functions can convert your strings to all UPPERCASE or all
lowercase. They are very useful for case sensitive operations where you may require all characters to
be lowercase .
Example
<?php
$name = "Matthew ";
echo strtoupper($name)."<br>"; // MATTHEW
echo strtolower($name); // matthew
?>
➢ Searching for a needle in a haystack: Sometimes we need to find a substring within a string and to
do that we can use strpos().
Syntax strpos ($haystack,$needle,$offset)
✓ $haystack :this is the string in which you are going to find the $needle starting from [0].
✓ $needle: this is what you are going to search for in the $haystack.
✓ $offset – (Optional) search will start from this number of characters counted from the beginning of
the string. Cannot be negative
<?php
$name = "Matthew ";
echo strpos($name, "M") ."<br>"; // 0
echo strpos($name, "hew"); // 4
echo strpos($name, "m"); // false
?>
Notice that the last example is false. That is because this function is case sensitive and could not find a
match.
We can almost make use of an if statement and some variables to make the strpos function more useful and
meaningful.
<?php
$string = "I am learning how to use PHP string functions! ";
$search = "JavaScript";
if(strpos($string, $search) === false) {
echo "Sorry we could not find '$search' in '$string'.";
}
?>
Others:
The ucfirst() function returns string converting first character into uppercase. It doesn't change the case of
other characters.
Example
<?php
$str="my name is KALISA";
$str=ucfirst($str);
echo $str;
?>
The lcfirst() function returns string converting first character into lowercase. It doesn't change the case of
other characters.
Example
<?php
$str="MY name IS KALISA";
$str=lcfirst($str);
echo $str;
?>
The ucwords() function returns string converting first character of each word into uppercase.
Example
<?php
$str="my name is Solange mujawamariya";
$str=ucwords($str);
echo $str;
?>
The strrev() function returns reversed string.
Example
<?php
$str="school";
$str=strrev($str);
echo $str;
?>

Arithmetic Manipulation Functions

As well as string manipulation function, PHP also has functions to manipulate numbers.

➢ Rounding numbers. One of the most commonly used math function is round(). This function rounds
numbers with decimal points up or down. You can round a number to an integer (whole number) or to
a floating point (decimal numbers).

Syntax: round($val, $precision, $mode)


✓ $val – is the value to be rounded.
✓ $precision – (optional) number of decimal places to round to.
✓ $mode – the type of rounding that occurs and can be one of the following:
<?php
$number = 3.55776232;
echo round($number) . "<br/>"; // 4
echo round($number, 1) . "<br/>"; // 3.6
echo round($number, 3) . "<br/>"; //3.558
?>
Other math functions for rounding are ceil() and floor(). If you simply need to round a number to the nearest
whole number then these functions are better suited to that purpose.
✓ ceil() – rounds fractions up.
✓ floor() – rounds fractions down.
<?php
$number = 3.55776232;
echo ceil($number) ."<br/>"; // 4
echo floor($number) . "<br/>"; // 3
?>
Both functions require a value and unlike round(), do not have any additional parameters.

➢ Generating Random Numbers: Another very common math function is rand() which returns a
random number between two numbers.
Syntax: rand($min, $max)
✓ $min – (optional) sets the lowest value to be returned. Default is 0
✓ $max – (optional) sets the maximum value to be returned
Default returns getrandmax(). Note: getrandmax() on some windows machines will return 32767. You will
need to specify a $max value in order to return a larger number.
<?php
echo rand(). "<br>";
echo rand(). "<br>";
echo rand(2, 10)."<br>";
echo getrandmax();
?>
Others:
The abs() function returns absolute value of given number. It returns an integer value but if you pass floating
point value, it returns a float value.
Example
<?php
echo abs(-7)."<br/>"; // 7 (integer)
echo abs(7)."<br/>"; //7 (integer)
echo abs(-7.2)."<br/>"; //7.2 (float/double)
?>
The sqrt() function returns square root of given argument.
Example
<?php
echo sqrt(16)."<br/>";// 4
echo sqrt(25)."<br/>";// 5
echo sqrt(7)."<br/>";// 2.6457513110646
?>

The decbin() function converts decimal number into binary. It returns binary number as a string.
Example
<?php
echo decbin(2)."<br/>";// 10
echo decbin(10)."<br/>";// 1010
echo decbin(22)."<br/>";// 10110
?>
The dechex() function converts decimal number into hexadecimal. It returns hexadecimal representation of
given number as a string
Example
<?php
echo dechex(2)."<br/>";// 2
echo dechex(10)."<br/>";// a
echo dechex(22)."<br/>";// 16
?>
The decoct() function converts decimal number into octal. It returns octal representation of given number as
a string.
Example
<?php
echo decoct (2)."<br/>";// 2
echo decoct (10)."<br/>";// 12
echo decoct (22)."<br/>";// 26
?>
The base_convert() function allows you to convert any base number to any base number. For example, you
can convert hexadecimal number to binary, hexadecimal to octal, binary to octal, octal to hexadecimal, binary
to decimal etc.
Syntax: base_convert ( string $number , int $frombase , int $tobase )
Example
<?php
$n1=10;
echo base_convert($n1,10,2)."<br/>";// 1010
?>
The bindec() function converts binary number into decimal.
Example
<?php
echo bindec(10)."<br/>";// 2
echo bindec(1010)."<br/>";// 10
echo bindec(1011)."<br/>";// 11
?>
Array Functions

Array or array() is itself a function that stores multiple values in to a single variable. Aside from the array()
function there are a number of other functions to manipulate arrays, here we will look at some of the most
common ones.

➢ Adding New Elements: Adding new elements to the end of an array can be achieved by calling the
array_push() function.
Syntax: array_push($array, $value1, $value2)
✓ $array – the array in which you are adding new elements to.
✓ $value1 – (required) is the first value to push onto the end of the $array.
✓ $value2 – (optional) is the second value to push onto the end of the $array. You can push as many
values as you need.

➢ Sorting an Array As well as adding items to an array we sometimes need to be able to sort them.
PHP has a handy function called sort() to do just that.
Syntax: Sort ($array, $sort_flags)
✓ $array – the array in which you wish to sort.
✓ $sort_flags – (optional) modifies the sorting behavior. By default the sorting behavior will reorganize
an array alphabetically or numerically.
<?php
$games = array( "Farcry", "Metal Gear", "Fallout", "Witcher", "Batman");
sort($games); // array to sort
echo join(", ", $games); //output - Batman, Fallout , Farcry , Metal Gear, Witcher
?>
In order to echo or print out sorted arrays we can use a function called join() which is an alias of another
function called implode(). Join(glue, array) or implode(glue, array) functions return a string from the
elements of an array and both have the same
Syntax:
✓ glue – (optional) also known as a separator is what to put between the array elements.
✓ array – (required) is the array to join to a string.
If you need to sort and reverse the order of any array then you can use a function called rsort(). It works
exactly the same way as sort() except the output is reversed.
<?php
$games = array( "Farcry", "Metal Gear", "Fallout", "Witcher", "Batman");
rsort($games); // array to sort
echo join(", ", $games);//output - Witcher, Metal Gear, Farcry, Fallout, Batman);
?>
Others
PHP array_change_key_case() function changes the case of all key of an array.
Note: It changes case of key only.
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
Example2
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
PHP count() function counts all elements in an array.
Example
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>
PHP array_reverse() function returns an array containing elements in reversed order.

Example
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
PHP array_intersect() function returns the intersection of two array. In other words, it returns the matching
elements of two array.
Example
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
PHP array_search() function searches the specified value in an array. It returns key if search is successful.
Example
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>

Summarize
By now you should have a good overview of some common PHP functions for handling strings, integers and
arrays.
Now for a simple exercise, the goal is:
1. Create an array and put 5 elements in it.
2. Sort and count the array.
3. Randomly select an element from the array
4. echo or print out the select item in upper or lower case.
Solution
<?php
// create an array
$new_names = array();
$names = array_push($new_names, "Emmanuel", "Medard", "Fautine", "Wellars","Baptiste");
// count number of items
$total_items = count($new_names);
// Sort the array
sort($new_names);
// Randomly select an item
$selected = rand(0, $total_items);
// echo or print in upper or lower case
echo strtoupper($new_names[$selected]);
?>

User-defined functions

Apart from its own functions, PHP also let’s you create your own functions.
A user defined function declaration starts with the word "function".
The basic syntax of a function that we create is:
function functionName() {
code to be executed;
}

Note: A function name can start with a letter or underscore (not a number) and function names are NOT
case-sensitive.
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the
beginning of the function code and the closing curly brace ( } ) indicates the end of the function. To call the
function, just write its name followed by closed parathesis. The function outputs is "Hello world!".
Example
<?php
function writeMsg(){
echo "Hello world!";
}
writeMsg(); // call the function
?>

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable. 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.
The following example has a function with one argument ($fname). When the familyName() function is
called, we also pass along a name (e.g. Jane), and the name is used inside the function, which outputs several
different first names, but an equal last name:
<?php
function familyName($fname) {
echo "$fname Rutare <br>";
}
familyName("Jane");
familyName("Huge");
familyName("Steven");
familyName("Jimmy");
familyName("Boris");
?>
The following example has a function with two arguments ($fname and $year):
<?php
function familyName($fname, $year) {
echo "$fname Rutare born in $year <br>";
}
familyName("Huge", "2005");
familyName("Steven", "2008");
familyName("Jimmy", "2013");
?>
PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions - Returning values


To let a function, return a value, use the return statement:
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = ".sum(5, 10) . "<br>";
echo "7 + 13 = ".sum(7, 13) . "<br>";
echo "2 + 4 = ".sum(2, 4);
?>

Function recursion
Recursion is a programming solution in which a function calls itself. It is used to solve a variety of problems,
all of which have in common a structure that contains repetition.
It is recommended to avoid recursive function call over 200 recursion level because it may smash the stack
and may cause the termination of script. A recursive function calls itself until it meets a stopping condition.
<?php
function display($number=0) {
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}
display(3);
?>
Example 2 : Factorial Number
<?php
function factorial($n) {
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorial ($n -1));
}
echo factorial(5);
?>
Super Global variables
Some predefined variables in PHP are "superglobals", which means that they are always accessible,
regardless of scope - and you can access them from any function, class or file without having to do anything
special.
Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in all scopes.
The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
Let’s explain some of the superglobals, and the rest will be explained in later chapters.

1. PHP $GLOBALS

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the
PHP script (also from within functions or methods).PHP stores all global variables in an array called
$GLOBALS[index]. The index holds the name of the variable. The example below shows how to use the
super global variable $GLOBALS:
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it is also accessible from
outside the function

2. PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and script
locations.
The example below shows how to use some of the elements in $_SERVER:

<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

The following table lists the most important elements that can go inside $_SERVER:
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface
(CGI) the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as
www.w3schools.com)
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as
Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information
protocol (such as HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page
(such as POST)
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as
1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a
query string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the current
request (such as utf-8,ISO-8859-1)
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not
reliable because not all user-agents support it)
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing
the current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing
the current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to
communicate with the web server
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently
executing script
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN
directive in the web server configuration file (if your
script runs on a virtual host, it will be the value defined
for that virtual host) (such as [email protected])
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the
web server for communication (such as 80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which
are added to server-generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page
3. PHP $_REQUEST

PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting
an HTML form. The example below shows a form with an input field and a submit button.
When a user submits the data by clicking on "Submit", the form data is sent to the file specified
in the action attribute of the <form> tag. In this example, we point to this file itself for
processing form data. If you wish to use another PHP file to process form data, replace that
with the filename of your choice. Then, we can use the super global variable $_REQUEST to
collect the value of the input field:

<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo "Your name is ". $name;
}
}
?>
</body>
</html>
4. PHP $_POST

PHP $_POST is a PHP superglobal variable which is used to collect form data after submitting
an HTML form with method="post". Is the most widely used to pass variables.
The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to the file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_POST to collect the value of the input field:

<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo"Your name is ". $name;
}
}
?>
</body>
</html>

5. PHP $_GET

PHP $_GET is a PHP superglobal variable which is used to collect form data after submitting
an HTML form with method="get". $_GET can also collect data sent in the URL. Assume
we have an HTML page that contains a hyperlink with parameters:

<html>
<body>
<a href="get_test.php?subject=PHP&web=W3schools.com">Test GET</a>
</body>
</html>

When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to
"get_test.php", and you can then access their values in "get_test.php" with $_GET.
The example below shows the code in "get_test.php":
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</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 File System allows us to create file, read file line by line, read
file character by character, write file, append file, delete file and close file.
PHP has many functions to work with normal files. Those functions are:

PHP readfile() Function

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


Assume we have a text file called "webdictionary.txt", stored on the server, the PHP code to
read the file and write it to the output is as follows:
<?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.

PHP Open File - fopen()

A better method to open files is with the fopen() function. This function gives you more
options than the readfile() function.
First parameter of fopen() contains name of the file which is to be opened and second
parameter tells about mode in which file needs to be opened
The file may be opened in one of the following modes:
Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. If file not exist then new file is created and if file
already exists then contents of file is erased.
a Open a file for write only. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already
exists
r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new file
if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already
exists
PHP Read File - fread()

After file is opened using fopen() the contents of data are read using fread(). 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"));
Example:
<?php
$filename = "webdictionary.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
echo $filedata;
?>
fwrite() – New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to written to file. It
can contain optional third argument where length of text to written is specified, e.g.,
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
PHP Close File - fclose()

The fclose() function is used to close an open file. It's a good programming practice to close
all files after you have finished with them. You don't want an open file running around on
your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we want to
close:
<?php
$filename = "webdictionary.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
echo $filedata;
fclose($file);
?>
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:

<?php
$myfile = fopen("webdictionary.txt", "r");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the next line.

PHP Read Single Character - fgetc()

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


Note: After a call to the fgetc() function, the file pointer moves to the next character.

PHP Delete File


In PHP, we can delete any file using unlink() function. The unlink() function accepts one
argument only: file name
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file
is deleted successfully otherwise FALSE.
<?php
$status=unlink('webdictionary.txt');
if($status){
echo "File deleted successfully";
}
else{
echo "Sorry!";
}
?>
Application of PHP Security concepts
PHP form handling
When we develop a website or a web application, we often have to create forms to take input
from users, like a Login form or a Registration form.
Creating a form on the webpage is accomplished using HTML, while PHP serves as a transport
for those values from the webpage to the server and then in further processing those values.
There are two ways the browser client can send information to the web server.
• The GET Method
• The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding.
In this scheme, name/value pairs are joined with equal signs and different pairs are separated
by the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric
characters are replaced with a hexadecimal values. After the information is encoded it is sent
to the server.
Understanding How HTML Form Works

Let's create a simple HTML form and try to understand how it works, what are the different
attributes available in the <form> tag and what are they used for.
<html>
<body>
<form action="form-handler.php" method="POST">
Name: <input type="text" name="name"> <br/>
Email: <input type="text" name="email"> <br/>
<input type="submit">
</form>
</body>
</html>
In the code above, we have used the <form> tag to create an HTML form, with input fields for
Name and Email along with submit button to submit the form-data.
In the <form> tag, we have two attributes, action and method, do you know what they are for?
➢ action: Using this attribute, we can specify the name of the file which will collect and
handle the form-data. In the example above, we have provided name of a Php file.
➢ method: This attribute specify the means of sending the form-data, whether it will be
submitted via POST method or GET method.
Below we have the same form with method as GET,
<html>
<body>
<form action="form-handler.php" method=" GET ">
Name: <input type="text" name="name"> <br/>
Email: <input type="text" name="email"> <br/>
<input type="submit">
</form>
</body>
</html>

PHP Form Handling with POST

If we specify the form method to be POST, then the form-data is sent to the server using the
HTTP POST method.
The information sent from an HTML form using the POST method is not visible to anyone.
For Example: localhost/ form-handler.php.php

Disadvantages of POST Method


➢ POST requests do not cache.
➢ POST requests never remain in the browser history.
➢ It is not possible to bookmark the page because the variables are not displayed in
URL.
Advantages of POST Method
➢ The POST method is useful for sending any sensitive information because the
information sent using the POST method is not visible to anyone.
➢ There is no limitation on size of data to be sent using the POST Method. You can
send a large amount of information using this method.
➢ Binary and ASCII data can also be sent using the POST method.
➢ Data security depends on the HTTP protocol because the information sent using the
POST method goes through the HTTP header. By using secure HTTP, you can ensure
that your data is safe.
Below, we have the code, to access the form-data in the Php file specified in
the action attribute of our HTML form.
<?php
// getting the value of name field
$name = $_POST["name"];
// getting the value of the email field
$email = $_POST["email"];
echo "Hi, ". $name . "<br>";
echo "Your email address: ". $email ."<br>";
?>
Output:
Hi, Steven
Your email address: [email protected]

You will get the above output, if you provide name as " Steven " and email address as "
[email protected] ".

PHP Form Handling with GET

If we specify the form method to be GET, then the form-data is sent to the server using the
HTTP GET method.

The information sent from an HTML form using the GET method is visible to everyone in
the browser's address bar, which means that all the variable names and their values will be
displayed in the URL. Therefore, the get method is not secured to send sensitive information.
For Example: localhost/form-handler.php?name=Steven&email= [email protected]

Disadvantages of GET Method


➢ That only a limited amount of information can be sent using the GET method. This
limit should not exceed 2048 characters.
➢ The GET method cannot be used to send binary data (such as images or word
documents) to the server.
➢ For security reasons, never use the GET method to send highly sensitive information
like username and password, because it shows them in the URL
Advantages of GET Method
➢ You can bookmark the page with the specific query string because the data sent by the
GET method is displayed in URL.
➢ GET requests can be cached.
➢ GET requests are always remained in the browser history.

Below, we have the code, to access the form-data in the Php file specified in
the action attribute of our HTML form, this time using the GET superglobal.
<?php
// getting the value of name field
$name = $_ GET ["name"];
// getting the value of the email field
$email = $_ GET ["email"];
echo "Hi, ". $name . "<br>";
echo "Your email address: ". $email ."<br>";
?>
Output:
Hi, Steven
Your email address: [email protected]

You will get the above output, if you provide name as " Steven " and email address as "
[email protected] ".
Again, the output remains the same. Developers prefer POST for sending form data.
The first step to process the form-data is to fetch the data using POST or GET
superglobals, once you have the data, you can do anything with it, display it on your
webpage, save the data into database, perform validations etc.
Form Validation in PHP

An HTML form contains various input fields such as text box, checkbox, radio buttons, submit
button, and checklist, etc. These input fields need to be validated, which ensures that the user
has entered information in all the required fields and also validates that the information
provided by the user is valid and correct.
There is no guarantee that the information provided by the user is always correct. PHP validates
the data at the server-side, which is submitted by HTML form. You need to validate a few
things:
1. Empty String
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
6. Input length

Empty String

The code below checks that the field is not empty. If the user leaves the required field empty,
it will show an error message. Put these lines of code to validate the required field.
<form action="empty.php" method="get">
Name:<input type="text" name="name"><br>
<input type="submit" name="submit">
</form>
<?php
$name = $_POST["name"];
if (empty ($_POST["name"])) {
$errMsg = "Error! You didn't enter the Name.";
echo $errMsg;
} else {
echo $name;
}
?>

Validate String

The code below checks that the field will contain only alphabets and whitespace, for example
- name. If the name field does not receive valid input from the user, then it will show an error
message:
<?php
$name = $_POST ["name"];
if (!preg_match ("/^[a-zA-z ]*$/", $name) ) {
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
} else {
echo $name;
}
?>

Validate Number

The below code validates that the field will only contain a numeric value. For example -Mobile
no. If the Mobile no field does not receive numeric data from the user, the code will display an
error message:
<?php
$mobileno = $_POST ["Mobile_no"];
if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
echo $mobileno;
}
?>
Validate Email
A valid email must contain @ and . symbols. PHP provides various methods to validate the
email address. Here, we will use regular expressions to validate the email address.
The below code validates the email address provided by the user through HTML form. If the
field does not contain a valid email address, then the code will display an error message:
<?php
$email = $_POST ["Email"];
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
if (!preg_match ($pattern, $email) ){
$ErrMsg = "Email is not valid.";
echo $ErrMsg;
} else {
echo "Your valid email address is: " .$email;
} ?>
Validate URL
The below code validates the URL of website provided by the user via HTML form. If the field
does not contain a valid URL, the code will display an error message, i.e., "URL is not valid".
<?php
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}
?>
Input Length Validation
The input length validation restricts the user to provide the value between the specified range,
for Example - Mobile Number. A valid mobile number must have 10 digits.
The given code will help you to apply the length validation on user input:
<?php
$Mobile= $_POST["Mobile"];
$length = strlen($Mobile);
if ($length != 10) {
$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else {
echo "Your Mobile number is: " . $Mobile;
}
?>
Button Click Validate
The below code validates that the user click on submit button and send the form data to the
server one of the following method - get or post.
<?php
if (isset ($_POST['submit']) {
echo "Submit button is clicked.";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Data is sent using POST method ";
}
} else {
echo "Data is not submitted";
}
?>
To do: Now we will apply all these validations to an HTML form to validate the fields.
Create a registration form using HTML and perform server-side validation.

State Management in PHP


HTTP is a stateless protocol which means every user request is processed independently and it
has nothing to do with the requests processed before it. Hence there is no way to store or send
any user specific details using HTTP protocol.
But in modern applications, user accounts are created and user specific information is shown
to different users, for which we need to have knowledge about who the user(or what he/she
wants to see etc) is on every webpage.

PHP provides for two different techniques for state management of your web application, they
are:
➢ Server Side State Management
➢ Client Side Server Management

Server Side State Management

In server side state management we store user specific information required to identify the user
on the server. And this information is available on every webpage.
In PHP we have Sessions for server side state management. PHP session variable is used to
store user session information like username, userid etc and the same can be retrieved by
accessing the session variable on any webpage of the web application until the session variable
is destroyed.

Client Side State Management


In client side state management the user specific information is stored at the client side i.e. in
the bowser. Again, this information is available on all the webpages of the web application.
In PHP we have Cookies for client side state management. Cookies are saved in the browser
with some data and expiry date(till when the cookie is valid).
One drawback of using cookie for state management is the user can easily access the cookie
stored in their browser and can even delete it.

PHP Cookies

Cookie is a small piece of information stored as a file in the user's browser by the web server.
It is used to recognize the user.
Once created, cookie is sent to the web server as header information with every HTTP request.
You can use cookie to save any data but it should not exceed 1K(1024 bytes) in size.
Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received at
the server side.
There are three steps involved in identifying returning users

➢ Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
➢ Browser stores this information on local machine for future use.
➢ When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.

In short, cookie can be created, sent and received at server end.

Note: PHP Cookie must be used before <html> tag.

Types of Cookies

There are two types of cookies, they are:


➢ Session Cookie: This type of cookies are temporary and are expire as soon as the
session ends or the browser is closed.
➢ Persistent Cookie: To make a cookie persistent we must provide it with an expiration
time. Then the cookie will only expire after the given expiration time, until then it will
be a valid cookie.
Creating a Cookie in PHP

In PHP we can create/set a cookie using the setcookie() function.


Below we have the syntax for the function,

setcookie(name, value, expire, path, domain, secure)

The first argument which defines the name of the cookie is mandatory, rest all are optional
arguments. Let's understand what are the available arguments that we can supply to
the setcookie() function to set a cookie.

Argument What is it for?

name Used to specify the name of the cookie. It is a mandatory argument. Name of the
cookie must be a string. and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
value This sets the value of the named variable and is the content that you actually want
to store. It is generally saved as a pair with name. For example, name
is userid and value is 7007, the userid for any user.
expire(y) Used to set the expiration time for a cookie (specify a future time in seconds since
00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible.)
If you do not provide any value, the cookie will be treated as a session cookie and
will expire when the browser is closed.
path This specifies the directories (web URL) for which the cookie is valid. A single
forward slash character ('/' ) permits the cookie to be valid for all directories
(domain).
domain This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. It can be used to limit access of cookie for
sub-domains. For example, if you set the domain value
as wwww.studytonight.com, then the cookie will be inaccessible
from blog.studytonight.com. All cookies are only valid for the host and domain
which created them.
secure/ This can be set to 1 to specify that the cookie should only be sent by secure
security transmission using HTTPS otherwise set to 0 which mean cookie can be sent by
regular HTTP.

Following example will create two cookies name and age these cookies will be expired after
one hour.
<?php
setcookie("name", "John Kamana", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>

So if we want to create a cookie to store the name of the user who visited your website, and
set an expiration time of a week, then we can do it like this,

<?php
setcookie("name", "Emmanuel", time()+60*60*24*7);
?>
Accessing Cookies with PHP
PHP provides many ways to access cookies and then retrieve it to show its value in the
HTML page. Simplest way is to use $_COOKIE global variable. Following example will
access all the cookies set in above example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
?>
</body>
</html>
To access a stored cookie we can use the isset() to check whether the cookie is set or not.
<?php
// set the cookie
setcookie("name", "Emmanuel", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["name"]))
{
echo "Cookie set with value: ".$_COOKIE["name"];
}
else
{
echo "cookie not set!";
}
?>
NOTE: setcookie() function should be placed before the starting HTML tag(<html>).

Updating Cookie in PHP

To update/modify a cookie, simply set it again. For example, if we want to update the name
stored in the cookie created above, we can do it using setcookie() method again. We just
update the value of name cookie

Deleting Cookie with PHP

Officially, to delete a cookie you should call setcookie() with the name argument only but
this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

<?php
// updating the cookie
setcookie("name", "Emmanuel", time() - 3600);
?>
<html>
<body>

<?php
echo "cookie name is deleted!";
?>
</body>
</html>

PHP Session

PHP session is used to store and pass information from one page to another temporarily (until
user close the website). Session is not stored on the user browser like Cookies, hence it is a
more secure option.

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. As we know HTTP is a stateless protocol, if a user visits a
webpage and perform some action, there is no way to remember what he did when the user
navigates to the next webpage; the web server does not know who you are or what you do,
because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple
pages (e.g. username, favorite color, etc). By default, session variables last until the user closes
the browser or after leaving the site, the server will terminate the session after a predetermined
period of time, commonly 30 minutes duration.
So; Session variables hold information about one single user, and are available to all pages in
one application.

PHP session technique is widely used in shopping websites where we need to store and pass
cart information e.g. username, product code, product name, product price etc from one page
to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.

Let's take a practical example, when you log into your facebook account, by providing your
email address and password, until and unless you logout, the web application remembers who
you are; this is accomplished by Session
When a user logs into their account on any web application, a session is created for them, and
in the session their username or userid or some other unique identifier is stored, which is then
used on the consecutive webpages to show information specific to that user. On logout, the
session is destroyed.

Before we move on to how to start, update and end a session in PHP, let's learn a few realworld
use of session.
➢ Web applications which require a user to login, use session to store user information,
so that on every webpage related information can be displayed to the user.
➢ In eCommerce websotes, shopping cart is generally saved as part of session.
I hope this gives you an idea about how you can utilize session in your web application.

Start a Session in PHP

PHP session_start() function is used to start the session. It starts a new or resumes existing
session. It returns existing session if session is created already. If session is not available, it
creates and returns new session.
NOTE: The function session_start() should be the first statement of the page, before any
HTML tag.
Data is stored in the session using session variable, which can be assigned different values
using global variable $_SESSION.
In simpler words, using the function session_start() we initialize the session, in which we can
store information using the session variable $_SESSION. These variables can be accessed
during lifetime of a session
Let's take an example, below we have a webpage with Php file named first_page.php
<?php
// start the session
session_start();
// set the session variable
$_SESSION["username"] = "Emmanuel";
$_SESSION["userid"] = "1";
?>
<html>
<body>
<?php
echo "Session variable is set.";
?>
<a href="second_page.php">Go to Second Page</a>
</body>
</html>

Getting PHP Session Variable Values

In the code above, we have started a session and set two session variables. Above webpage will
also have a link to navigate to Second page second_page.php.
Below is the code for second_page.php, in which we fetch values from the session variable
which are set in the first_page.php.
<?php
// start the session
session_start();
// get the session variable values
$username = $_SESSION["username"];
$userid = $_SESSION["userid"];
?>
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>
</body>
</html>

Update Session Variable in PHP

To update any value stored in the session variable, start the session by
calling session_start() function and then simply overwrite the vakue to update session
variable.
<?php
// start the session
session_start();
// update the session variable values
$_SESSION["userid"] = "11";
?>
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>
</body>
</html>

Destroy a Session in PHP

A PHP session can be destroyed by session_destroy() function. This function does not need
any argument and a single call can destroy all the session variables.
If you want to destroy a single session variable then you can use unset() function to unset a
session variable.
Here is the example to unset a single variable:
<?php
unset($_SESSION['userid']);
?>
Here is the call which will destroy all the session variables:
<?php
session_destroy();
?>
To clean the session variable or to remove all the stored values from the session variable we
can use the function session_unset()
We use these functions on pages like logout or checkout in case of an eCommerce website to
clean the session variable off the user specific data and to eventually destroy the current session.

Make use of isset() function to check if session variable is already set or not.
<?php
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter']."in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo $msg ; ?>
</body>
</html>

You might also like