You are on page 1of 104

Unit-4

PHP
Syllabus

Introduction and basic syntax of PHP, decision and looping with examples, PHP and HTML, Arrays,
Functions, Browser control and detection, string, Form processing, Files, Advance Features: Cookies
and Sessions, Object Oriented Programming with PHP
Introduction
 The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to
create dynamic content that interacts with databases. PHP is basically used for developing web
based software applications.
 PHP is an interpreted language, i.e., there is no need for compilation.
 PHP is faster than other scripting languages, for example, ASP and JSP.
 PHP is a server-side scripting language, which is used to manage the dynamic content of the
website.
 PHP can be embedded into HTML.
 PHP is an object-oriented language.
 PHP is an open-source scripting language.
 PHP is simple and easy to learn language.
Features of PHP

 Embedded inside HTML, easy to develop FOSS


 Easy to manage dynamic content, database, session tracking
 Supports many internet protocols such as LDAP, IMAP, POP3
 Supports many databases such as MS SQL server, Oracle, SyBase, PostgreSQL, MySQL,
etc
Applications of PHP

 PHP is one of the most widely used language over the web.
 PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, through email
you can send data, return data to the user.
 You add, delete, modify elements within your database through PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.
PHP Syntax

 A PHP script can be placed anywhere in the document.


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

<?php
// PHP code goes here
?>
 The default file extension for PHP files is ".php".
 A PHP file normally contains HTML tags, and some PHP scripting code.
PHP Echo
 PHP echo is a language construct, not a function.
 PHP echo statement can be used to print the string, multi-line strings, escaping characters, variable, array,
etc
 Example
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
PHP Variables
 In PHP, a variable is declared using a $ sign followed by the variable name.
 As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
Rules for PHP variables:
 A variable starts 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)
Example
<!DOCTYPE html>
<html>
<body>

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;

echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>

</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
 PHP is Case Sensitive, so $color, $COLOR, and $coLOR are treated as three different
variables.
PHP echo and print Statements

 With PHP, there are two basic ways to get output: echo and print.
 The differences are: echo has no return value while print has a return value of 1 so it can
be used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.
Example
<!DOCTYPE html>
<html>
<body>

<?php
print "<h2>PHP </h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>

</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>

<?php
echo "<h2>PHP </h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

</body>
</html>
PHP - Decision Making

The conditional statements are used to perform different actions based on the different
conditions.
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed
PHP - The if Statement

 The if statement executes some code if one condition is true.

 Syntax
if (condition) {
code to be executed if condition is true;
}
Example
<!DOCTYPE html>
<html>
<body>

<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>

</body>
</html>
PHP - The if...else Statement

 The if...else statement executes some code if a condition is true and another code if
that condition is false.
 Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
<!DOCTYPE html>
<html>
<body>

<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>

</body>
</html>
Example
PHP - The if...else..if Statement
 The if...elseif...else statement executes different codes for more than two conditions.

 Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example
<?php  
    $marks=69;      
    if ($marks<33){    
        echo "fail";    
    }    
    else if ($marks>=34 && $marks<50) {    
        echo "D grade";    
    }    
    else if ($marks>=50 && $marks<65) {    
       echo "C grade";   
    }    
    else if ($marks>=65 && $marks<80) {    
        echo "B grade";   
    }    
    else if ($marks>=80 && $marks<90) {    
        echo "A grade";    
    }  
    else if ($marks>=90 && $marks<100) {    
        echo "A+ grade";   
    }  
   else {    
        echo "Invalid input";    
    }    
?> 
PHP - The switch Statement
switch (expression){
case label1:
code to be executed if expression = label1;
break;

case label2:
code to be executed if expression = label2;
break;

default:
code to be executed
if expression is different
from both label1 and label2;
}
Example
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue": Output:
echo "Your favorite color is blue!"; Your favorite color is red!
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
break;
}
?>
PHP break

 The PHP break keyword is used to terminate the execution of a loop prematurely. The
break statement is situated inside the statement block. If 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.
Example

<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )
break;
}
echo ("Loop stopped prematurely at i = $i" );
?>
Output: Loop stopped prematurely at i = 3
PHP continue

 The PHP continue keyword is used to halt the current iteration of a loop but it
does not terminate the loop. Just like the break statement the continue
statement is situated inside the statement block containing the code that the
loop executes, preceded by a conditional test. For the pass encountering
continue statement, rest of the loop code is skipped and next pass starts.
Example
<?php
$array = array( 1, 2, 3, 4, 5);
foreach ( $array as $value )
{
Output
if( $value == 3 )
{ continue; Value is 1
Value is 2
} Value is 4
echo "Value is $value <br />"; Value is 5
}
?>
PHP Loops

In PHP, we have the following loop types:


 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as
the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array
 The while loop - Loops through a block of code as long as the specified condition is
true.
 Syntax
while (condition is true)
{
  code to be executed;
}
Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = 0;
while($x <= 100) {
echo "The number is: $x <br>";
$x+=10;
}
?>
</body>
</html>
 The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
 Syntax
do {
  code to be executed;
} while (condition is true);
Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

</body>
</html>
 The for loop - Loops through a block of code a specified number of times.
 The for loop is used when you know in advance how many times the script should run.
 Syntax

for (init counter; test counter; increment counter)


{
  code to be executed for each iteration;
}
Example
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

</body>
</html>
 The foreach loop - Loops through a block of code for each element in an array.
 The foreach loop works only on arrays, and is used to loop through each key/value pair
in an array.
 Syntax
foreach ($array as $value)
{
  code to be executed;
}
 For every loop iteration, the value of the current array element is assigned to $value
and the array pointer is moved by one, until it reaches the last array element.
Example
<!DOCTYPE html>
<html>
<body>

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

</body>
</html>
Example

<!DOCTYPE html>
<html>
<body>
<?php $array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{ echo "Value is $value <br />"; }
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $val) {


echo "$x = $val<br>";
}
?>

</body>
</html>
PHP Arrays

 An array stores multiple values in one single variable in similar type.


 In PHP, the array() function is used to create an array.
PHP Array Types
 There are 3 types of array in PHP.
1. Indexed Array -  An array with a numeric index.
2. Associative Array- An array with strings as index.
3. Multidimensional Array- Arrays containing one or more arrays
Indexed Array
 PHP index is represented by number which starts from 0. We can store
number, string and object in the PHP array. All PHP array elements are
assigned to an index number by default.
 There are two ways to define indexed array:
1. $season=array("summer","winter","spring","autumn");  
2. $season[0]="summer";  

$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  
Example
First method
<?php  
$season=array("summer","winter","spring","autumn");  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?> 

Second method
<?php  
$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?>  
Example
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5); OUTPUT
foreach( $numbers as $value )
{ Value is 1
echo "Value is $value <br />"; Value is 2
} Value is 3
/* Second method to create array. */ Value is 4
$numbers[0] = "one"; Value is 5
$numbers[1] = "two"; Value is one
$numbers[2] = "three"; Value is two
$numbers[3] = "four"; Value is
$numbers[4] = "five"; three Value
foreach( $numbers as $value ) is four Value
{ is five
echo "Value is $value <br />";
}
?>
</body> </html>
Associative Array
 Associative array will have their index as string so that you can establish a strong association
between key and values.
 There are two ways to define associative array:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");  
2. $salary["Sonoo"]="350000";  
$salary["John"]="450000";  
$salary["Kartik"]="200000";  
Example
<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, “John" => 1000, "zara" => 500);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


OUTPUT
echo "Salary of John is ". $salaries[‘John']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
Salary of mohammad is
/* Second method to create array. */ 2000 Salary of John is 1000
$salaries['mohammad'] = "high"; Salary of zara is 500
$salaries[' John '] = "medium"; Salary of mohammad is
$salaries['zara'] = "low"; high Salary of John is
medium
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
Salary of zara is low
echo "Salary of John is ". $salaries[' John ']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>
Multidimensional Arrays
 A multi-dimensional array each element in the main array can also be an
array. And each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using multiple index.
Example
 In this example we create a two dimensional array to store marks of three students in three subjects −
<html>
<body>

<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

“John" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"zara" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for John in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;


echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
OUTPUT
</html>
Marks for mohammad in physics :
35 Marks for qadir in maths : 32
Marks for zara in chemistry : 39
Functions
 Function is a set of statements that perform a specific task and can be executed at any
time. PHP defines several built in functions and also supports user –defined function.
 The general syntax of a PHP function is as follows,
function function_name(args 1, args 2, …., args n )
{ // block of codes / statements;
}
Example
<?php
average();
function average()
{
$sub1=50;
$sub2=50;
$total = $sub1 + $sub2;
$avg = $total / 2;
echo “The Average is: $avg”;
}
?>
PHP Functions with Parameters
Information can be passed to functions through arguments. An argument is just like a
variable.
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>
Example
<?php
function familyName($fname) {
  echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Default Argument Value
<?php 
function setHeight(int $minheight = 50)
{
  echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Functions returning value
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>
Example
<?php  
function cube($n){  
return $n*$n*$n;  
}  
echo "Cube of 3 is: ".cube(3);  
?> 
Browser control

 PHP can control various features of a browser.


 There is a need to reload the same page or redirect the user to another one.
 These features are accessed by controlling the information sent out in the
HTTP header to the broswser. This uses the header() command such as
header(“Loacation: index.html”);
It redirects to the index.html page
Example
<?php
// This will redirect the user to the new location
header('Location: http://www.gmail.com/');

//The below code will not execute after header


exit;
?>
 To reload the current page

<?php
header(“Cache-Control: no-cache”);
$self=$SERVER[‘PHP_SELF];

?>

<form action=“<?php $self ?>” method = “post”>


 Initially, header information is sent, instructing to always reload the page rather than
relying on a cached version.
 The $self variable, defines it as having the value of the URL of this page.
 A form can utilize the $self variable to actually point at this page, so the data collected
can be checked and if it is not correct, the form can be re-displayed.
Browser detection

 It is important to know which browser and other details you are dealing with in order to
appropriately render the web page.
 The browser that the server is dealing with can be identified using:
$browser_ID=$_SERVER[‘HTTP_USER_AGENT’];
 $_SERVER is a global array with lots of useful information stored in it about the server’s
current status.
 The HTTP_USER_AGENT is an environmental variable that contains information.
 Eg1
Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebkit /312.1 (KHTML, like Gecko)
Safari/312
This shows the Safari browser running on Mac OS X.
 Eg2
Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-0; en-US; rv:1.7.6) Gecko/20050225
Firefox/1.0.1
This shows the Firefox running on Mac OS X.
PHP Strings

 A string is a sequence of characters.


 Eg- "Hello world!".
 Strings enclosed in double quotes are the most commonly used in PHP scripts because
they offer the most flexibility. Escape sequences are also parsed.
Example
<?php
$output = "This is one line.\n And this is another line.";
echo $output;
?>
PHP String Functions

1. strlen() - Return the Length of a String


Example
<?php
echo strlen("Hello world!");  // outputs 12
?>
2. str_word_count() - Count Words in a String
<?php
echo str_word_count("Hello world!");  // outputs 2
?>
3. strrev() - Reverse a String
<?php
echo strrev("Hello world!");  // outputs !dlrow olleH
?>

4. strpos() - Search For a Text Within a String


 If a match is found, the function returns the character position of the first match. If no
match is found, it will return FALSE.
<?php
echo strpos("Hello world!", "world");  // outputs 6
?>
5. str_replace() - Replace Text Within a String
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
 It replace the text "world" with "Dolly“.
PHP-Form Processing


The PHP superglobals $_GET and $_POST are used to collect form-data .
Example
<!DOCTYPE HTML>  
<html>
<head>
</head>
<body>  

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name">
  <br><br>
  E-mail: <input type="text" name="email">
  <br><br>
  Website: <input type="text" name="website">
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" value="female">Female
  <input type="radio" name="gender" value="male">Male
  <input type="radio" name="gender" value="other">Other
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>
Output
 $_SERVER["PHP_SELF"] variable

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently
executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of
jumping to a different page.

 htmlspecialchars() function

The htmlspecialchars() function converts special characters to HTML entities. This means
that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers
from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks)
in forms.
 PHP trim() function -Strip unnecessary characters (extra space, tab, newline) from the
user input data.
 PHP stripslashes() function - Remove backslashes (\) from the user input data
PHP-Files
 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 Open File - fopen()
 The first parameter of fopen() contains the name of the file to be opened and the
second parameter specifies in which mode the file should be opened.
 Example
<?php
$myfile = fopen("web.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
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. 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 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()
 The fread() function reads from an open file.
 The first parameter of fread() contains the name of the file to read from and the
second parameter specifies the maximum number of bytes to read.
fread($myfile,filesize(“web.txt"));

 PHP Close File - fclose()


 The fclose() function is used to close an open file.
<?php
$myfile = fopen(“web.txt", "r");
// some code to be executed....
fclose($myfile);
?>
 PHP Read Single Line - fgets()
 The fgets() function is used to read a single line from a file.
<?php
$myfile = fopen(“web.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
 PHP Check End-Of-File - feof()
 The feof() function checks if the "end-of-file" (EOF) has been reached.
 PHP Read Single Character - fgetc()
 The fgetc() function is used to read a single character from a file.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
  echo fgetc($myfile);
}
fclose($myfile);
?>
 PHP Write to File - fwrite()
 The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
 Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Example

The following example assigns the content of a text file to a variable then displays those contents on the web
page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>

<body>
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );
fclose( $file );

echo ( "File size : $filesize bytes" );


echo ( "<pre>$filetext</pre>" );
?>
</body>
PHP cookies
 A cookie is often used to identify a user. A cookie is a small file that the server embeds
on the user's computer. Each time the same computer requests a page with a browser,
it will send the cookie too. With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
 A cookie is created with the setcookie() function.
 Syntax
setcookie(name, value, expire, path, domain, secure, http only);
Only the name parameter is required. All other parameters are optional.
 PHP Create/Retrieve a Cookie

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

<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>.
use isset() function to check if a cookie is set or not.

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
 Deleting Cookie with PHP
<?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 Sessions

A PHP session variable is used to store information about, or


change settings for a user session.
 Session variables hold information about one single user, and
are available to all pages in one application.
 PHP Session Variables
 When you are working with an application, you open it, do some changes and then you close
it.
 This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end.
 But on the internet there is one problem: the web server does not know who you are and what
you do because the HTTP address doesn't maintain state.
 A PHP session solves this problem by allowing you to store user information on the server for
later use (i.e. username, shopping items, etc). However, session information is temporary and
will be deleted after the user has left the website. If you need a permanent storage you may
want to store the data in a database.
 Sessions work by creating a unique id (UID) for each visitor and store variables based on this
UID. The UID is either stored in a cookie or is propagated in the URL.
 Storing a Session Variable
 The correct way to store and retrieve session variables is to use the PHP
$_SESSION variable:

<?php session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>

Output: Pageviews=1
 In the example below, we create a simple page-views counter. The
isset() function checks if the "views" variable has already been set.
If "views" has been set, we can increment our counter. If "views"
doesn't exist, we create a "views" variable, and set it to 1:

<?php session_start();
 if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
 Destroying a Session
 If you wish to delete some session data, you can use the unset() or the session_destroy()
function.
 The unset() function is used to free the specified session variable:

<?php unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php session_destroy();
?>

 session_destroy() will reset your session and you will lose all your stored session data.
Difference between cookies and sessions
Object Oriented Programming with PHP

 OOP stands for Object-Oriented Programming.


 Procedural programming is about writing procedures or functions that
perform operations on the data, while object-oriented programming is about
creating objects that contain both data and functions.
advantages

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and
shorter development time
OOPs- Principles

The three major principles of OOP are;


 Encapsulation – this is concerned with hiding the implementation details and only
exposing the methods. The main purpose of encapsulation is to;
 Reduce software development complexity – by hiding the implementation details and
only exposing the operations, using a class becomes easy.
 Protect the internal state of an object – access to the class variables is via methods
such as get and set, this makes the class flexible and easy to maintain.
 The internal implementation of the class can be changed without worrying about
breaking the code that uses the class.
 Inheritance – this is concerned with the relationship between classes. The relationship
takes the form of a parent and child. The child uses the methods defined in the parent
class. The main purpose of inheritance is;
 Re-usability– a number of children, can inherit from the same parent. This is very useful
when we have to provide common functionality such as adding, updating and deleting
data from the database.

 Polymorphism – this is concerned with having a single form but many different
implementation ways. The main purpose of polymorphism is;
 Simplify maintaining applications and making them more extendable.
OOPs Concepts in PHP

 The OOPs principles are achieved via;


 Encapsulation – via the use of “get” and “set” methods etc.
 Inheritance – via the use of extends keyword
 Polymorphism – via the use of implements keyword
Classes and Objects

 A class is a template for objects, and an object is an instance of a class.


 When the individual objects are created, they inherit all the properties and behaviors
from the class, but each object will have different values for the properties.
 Eg for class – Car and their objects- Volvo, Audi, Toyota.

Defining PHP Classes

 A class is defined by using the class keyword.


 Syntax
<?php
class Fruit {
  // code goes here...
}
?>
Define Objects

 Objects of a class is created using the new keyword.


 We can create multiple objects from a class. Each object has all the
properties and methods defined in the class, but they will have different
property values.
Example of classes and objects
<?php  
class demo  
{  
        private $a= ”Hello”;  
        public function display()  
        {  
        echo $this->a;  
        }  
}  
$obj = new demo();  
    $obj->display();  
?>  
 The variable $this is a special variable and it refers to the same object ie. itself.
  There are two kinds of public methods
 A get method returns the value of the private property.
 A set method a new value for the private property.
Example
<?php
class Fruit {
$apple = new Fruit();

// Properties $banana = new Fruit();


public $name; $apple->set_name('Apple');
public $color; $banana->set_name('Banana');

// Methods echo $apple->get_name();


function set_name($name) { echo "<br>";
$this->name = $name; echo $banana->get_name();
}
?>
function get_name() {
return $this->name;
}
}
Constructor

 Constructor Functions are special type of functions which are called


automatically whenever an object is created.
 A constructor allows you to initialize an object's properties upon creation of
the object.
 Use __construct() to define a constructor.
Constructor
<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>
Destructor

 A destructor is called when the object is destructed or the script is stopped or


exited.
 Use __destruct() function to destroy.
 PHP will automatically call this function at the end of the script.
Inheritance

 Inheritance allows a class to reuse the code from another class without


duplicating it.
 In inheritance, you have a parent class with properties and methods, and
a child class can use the code from the parent class.
 Inheritance allows you to write the code in the parent class and use it in both
parent and child classes.
 To define a class inherits from another class, you use the extends keyword.
Syntax
class Child extends Parent {
<definition body>
}
Example
<?php
class Fruit {
  public $name;
  public $color;
  public function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
 }
  public function intro() {
    echo "The fruit is {$this->name} and the color is {$this->color}.";
 }
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
  public function message() {
    echo "Am I a fruit or a berry? ";
 }
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>

You might also like