Term1 PHP Programming
Term1 PHP Programming
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.
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.
<?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
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)
Multi-line Comments:
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.
Parameter Description
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
Because the condition is false, the result in this case would be:
You are an adult
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:
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);
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
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; ?>
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");
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 " "; // it will print blank space
}
for ($j = 1; $j <= $i; $j++) {
echo " * ";
}
echo '<br />';
}
?>
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>";
}
?>
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
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>";
}
}
?>
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;
?>
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).
➢ 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
?>
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);
?>
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>
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.
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>
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
You will get the above output, if you provide name as " Steven " and email address as "
[email protected] ".
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]
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.
PHP provides for two different techniques for state management of your web application, they
are:
➢ Server Side State Management
➢ Client Side Server 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.
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.
Types of Cookies
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.
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>).
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
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.
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>
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>
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>
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>