You are on page 1of 48

Chapter 5

Cookies and sessions

2023 GC.
Introduction
What is a Cookie?
 A cookie is a small file that the server embeds on

the user's computer.


 A cookie is often used to identify a user.

 Each time the same computer requests a page with

a browser, it will send the cookie too.


 With PHP, You can store information in cookies

and then retrieve it.


 You store cookies by using the setcookie()

function.
Cookies and Sessions…

 The general format is as follows:


setcookie(“variable", "value”);
setcookie(variable_name, value, expire);
 Only the variable_name parameter is required. All other

parameters are optional.


 The variable is the variable name, but you do not include the

dollar sign ($).


 This statement stores the information only until the user

leaves your Web site.


 For example, the following statement stores the pair

city=Jimma in the cookie file on the user’s computer:


setcookie(“city”,”Jimma”);
Cookies and Sessions…
 When the user moves to the next page, the cookie information is available
in the built-in array called $_COOKIE, retrieve the value of the cookie.
 We also use the isset() function to find out if the cookie is set
 The next Web page can display the information from the cookie by using
the following statement.
echo “Your home city is “.$_COOKIE[‘city’];

 The output from this statement is as follows:


Your home city is Jimma

Setting expiration dates


 If you want the information stored in a cookie to remain in a file on the

user’s computer after the user leaves your Web site, set your cookie with
an expiration time, as follows:
setcookie(“variable”,”value”,expiretime);
Cookies and Sessions…
 The expiretime value sets the time when the cookie expires.
 The value for expiretime is usually set by using either the
time or mktime function as follows:
 time: This function returns the current time in a format the
computer can understand.
 You use the time function plus a number of seconds to set the
expiration time of the cookie:
setcookie(“state”, ”CA”, time()+3600); #expires in one hour
$Name=“three_days”;
setcookie(“Name”, $Name, time()+(3*86400)) #expires 3
days
Cookies and Sessions…
 mktime: This function returns a date and time in a
format that the computer can understand. You must
provide the desired date and time in the following
order: hour, minute, second, month, day, and year. If
any value is not included, the current value is used.

 This is shown in the following statements:


setcookie(“state”, ”CA”, mktime(3,0,0,4,1,2003));
#expires at 3:00 AM on April 1, 2003
setcookie(“state”, ”CA”, mktime(13,0,0,,,));
/#expires at 1:00 PM today
Cookies and Sessions…
Example2:
Using isset() function
//Here set your cookie with an expiration time, for one day.
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
?>
Cont.
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the value of
the cookie.</p>
</body>
</html>
Output is
Cookie 'user' is set!
Value is: John Doe
Cont.
 Note: The setcookie() function must appear
BEFORE the <html> tag.
 Note: The value of the cookie is automatically
URLencoded when sending the cookie, and
automatically decoded when received (to prevent
URLencoding, use setrawcookie() instead).
Cont.
Deleting a Cookie
 Officially, to delete a cookie, you should call setcookie() with the name
argument only:
setcookie("vegetable");
 This approach does not always work well, however, and should not be
relied on.

 It is safest to set the cookie with a date you are sure has already expired:
setcookie("vegetable", "", time()-60);
 You should also ensure that you pass setcookie() the same path, domain,
and secure parameters as you did when originally setting the cookie.
Cont.
<!DOCTYPE html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>
Output
Cookie 'user' is deleted.
</body>
</html>
Check if Cookies are Enabled
 The following example creates a small script that checks whether cookies are enabled.
 First, try to create a test cookie with the setcookie() function, then count the $_COOKIE
array variable:
<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

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

</body>
</html>
Cont.
What is a PHP Session?
 A session is a way to store information (in variables) to be used

across multiple pages.


 After you create a session, the session variables are available for your

use on any other Web page.


 To make session information available, PHP does the following:

 PHP assigns a session ID number.


 The number is a really long number that is unique for the user and that no
one could possibly guess. The session ID is stored in a PHP system
variable named PHPSESSID.
 PHP stores the variables that you want saved for the session in a file on the
server.
 The file is named with the session ID number.
 It’s stored in a directory specified by session.save_path in the php.ini file.
 PHP passes the session ID number to every page.
Why we use session?
 Whenever you want to create a website that allows you to store
and display information about a user, determine which user
groups a person belongs to, utilize permissions on your
website or you just want to do something cool on your site,
PHP's Sessions are vital to each of these features.
 PHP has a great set of functions that can achieve the same
results of Cookies and more without storing information on the
user's computer. PHP Sessions store the information on the web
server. These files are connected to the user's web browser via
the server and a special ID called a "Session ID". This is nearly
99% flawless in operation and it is virtually invisible to the
user.
 Sessions store their identifier in a cookie in the client’s browser
Cont.
Start a PHP Session
 You should open/start a session at the beginning of each

Web page.
 A session is started with the Session_start() function, as

follows:
session_start();
 The function first checks for an existing session ID number.

 If it finds one, it sets up the session variables.

 If it doesn’t find one, it starts a new session by creating a

new session ID number.


 Note: The session_start() function must be the very first

thing in your document. Before any HTML tags.


Cont.
Using PHP session variables
 To save a variable in a session so that it’s available on later

Web pages, store the value in the $_SESSION array, as


follows:
 Session variables are set with the PHP global variable:

$_SESSION.
$_SESSION[‘varname’] = “John Bonson”;
 When you open a session on any subsequent Web page, the

values stored in the $_SESSION array are available.

 If you want to stop storing any variable at any time, you can
unset the variable by using the following statement:
unset($_SESSION[‘varname’]);
Cont.
Now, let's create a new page called "session1.php".
In this page, we start a new PHP session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body> Output
<?php Session variables are set.
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
Cont.
Get PHP Session Variable Values
 Next, we create another page called
"session2.php". From this page, we will access the
session information we set on the first page
("session1.php").
 Notice that session variables are not passed
individually to each new page, instead they are
retrieved from the session we open at the beginning
of each page (session_start()).
Cont.
Example2
<?php
session_start();
?> Output
<!DOCTYPE html> Favorite color is green.
Favorite animal is cat.
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Cont.
Another way to show all the session variable values for a user session is to
run the following code:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php Output
print_r($_SESSION); Array ( [favcolor] => green [favanimal] => cat )
?>
</body>
</html>
Destroying a Session
 You may want to restrict your site to users
with a valid user ID and password.
 For restricted sessions that users log into, you

often want users to log out when they’re


finished.
 To close a session, use the following statement

wherever to want to close the session:


session_destroy();
Cont.
The following two scripts show how to use sessions to pass information from one page to the
next.
<?php
/* Script name: sessionTest1.php */
session_start();
$_SESSION[‘fullName’] = “David John Antony”;
?>
<html>
<head><title>Testing Sessions page 1</title></head>
<body>
<p>This is a test of the sessions feature.
<form action=”sessionTest2.php” method=”POST”>
<input type=”text” name=”form_var” value=”testing”>
<input type=”submit” value=”Go to Next Page”>
</form>
</body>
Cont.
 In this script, a session is started and one session variable called fullName
is stored.
 A form is also displayed with one text field where the user can enter some
text.
 When the submit button from this form, labeled “Go to Next Page” is
clicked, the sessionTest2.php script runs.
<?php
/* Script name: sessionTest2.php */
session_start();
$session_var = $_SESSION[‘fullName’];
$form_var = $_POST[‘form_var’];
echo “session_var = $session_var<br>\n”;
echo “form_var = $form_var<br>\n”;
1.8 Cookies and Sessions…
 Output:
session_var = David John Antony
form_var = testing
Reusing Code
 One of the goals of software engineers is to reuse code in lieu of writing
new code.
 Reusing existing code reduces costs, increases reliability, and improves
consistency.
 Ideally, a new project is created by combining existing reusable
components, with a minimum of development from scratch.

 PHP provides too very simple, yet very useful, statements to allow you to
reuse any type of code.
 Using include or require statement, you can load a file into your PHP
script.
 The file can contain anything you would normally type in a script
including PHP statements, text, HTML tags, etc
Reusing Code…
 The two functions are identical in every way, except how they
handle errors:
 include() generates a warning (E_WARNING), but the

script will continue execution


 require() generates a fatal error (E_COMPILE_ERROR),

and the script will stop

 These two functions are used to create functions, headers,


footers, or elements that will be reused on multiple pages.
Reusing Code…
Using require:
 The following code is stored in a file named reusable.php:

<?php
echo “Here is a very simple PHP statement. <br>”;
?>

 The following code is stored in a file called main.php:


<?php
echo “This is the main file. <br> “;
require(“reusable.php”);
echo ”The script will end now. <br>”;
?>
Reusing Code…
 Output
This is the main file.
Here is a very simple PHP statement.
The script will end now.
Reusing Code…
Using include:
 The statements require() and include() are very similar, but

some important differences exist in the way they work.


 The require statement is also used to include a file into the

PHP code.
 However, there is one big difference between include and

require; when a file is included with the include statement and


PHP cannot find it, the script will continue to execute:
Reusing Code…
 Assume we have a standard footer file called "footer.php", that looks like
this:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>
 To include the footer file in a page, use the include statement:

Example
<?php
<html>
<body>
<h1>Welcome to my home page!</h1> Output
<p>Some text.</p> Welcome to my home page!
<p>Some more text.</p> Some text.
include (“footer.php”); Some more text.
?> Copyright © 1999-2016 W3Schools.com
</body>
Include Vs. Require example
 Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
 Then, if we include the "vars.php" file, the variables can be used in the

calling file:
Example
<html>
<body>
<?php
<h1>Welcome to my home page!</h1> Output
include (“vars.php”); Welcome to my home page!
echo "I have a $color $car."; I have a red BMW.
?>
</body>
</html>
Include Vs. Require example
 If we require the "vars.php" file, the variables can be used in the calling file:
Example
<html>
<body>
<?php
<h1>Welcome to my home page!</h1>
require (“vars.php”);
echo "I have a $color $car.";
?>
</body> Output
</html> Welcome to my home page!
I have a red BMW.

The output is the same with the previous example, because the purpose of using
both of them are the same but, if the file is not found there will give different out
put
Include Vs. Require example
 If the file name not match which reuses on other page by using include() or
require() function, we can observe the output difference when using include
and require reusing functions. Take the file name "vars2.php" file, the
variables can be used in the calling file:
Example
<html>
<body>
<?php
<h1>Welcome to my home page!</h1> Output
require (“vars2.php”); Welcome to my home page!
echo "I have a $color $car.";
?>
</body>
</html>

Here when using required() function the script is stop execution after
Include Vs. Require example
 When we use include() instead of require() the out put will be:
Example
<html>
<body>
<?php
<h1>Welcome to my home page!</h1>
require (“vars2.php”); Output
Welcome to my home page!
echo "I have a $color $car.";
I have a
?>
</body>
</html>

 But here when using include() function the script is continue


execution after displaying the first statement even if dose not find
the reusing file.
Include Vs. Require example
 Use require when the file is required by the
application.
 Use include when the file is not required and
application should continue when file is not found.
Classes in PHP
 The basic elements of object-oriented programs are objects. It’s
easiest to understand objects as physical objects.
 For example, a car is an object.
 A car has properties, such as color, model, engine, and tires, also
called attributes.
 A car has things it can do, too, such as move forward, move
backward, park, roll over, and play dead (well, mine does
anyway).

 A class is the script that serves as the template that is used to


create an object.
 The class defines the properties, the attributes, of the object.
 It also defines the things the object can do — its responsibilities.
Classes in PHP…
Defining a Class
 A minimal class definition looks as follows:

class classname
{
//code
}
 In order to be useful, our classes need attributes and operations.

 We create attributes by declaring variables within a class definition

using the keyword var.


 The following code creates a class called car with two attributes,

$name and $speed.


 We create operations by declaring functions within the class definition.

 The following code will create a class named car with two operations.
Classes in PHP…
class car
{
var $name;
var $speed;
function moveforward() //operation1
{
//code here
}
function reverse($param1, $param2) //operation2
{
//code here
}
}
Classes in PHP…
Constructors
 Most classes will have a special type of operation called a constructor.
 A constructor is called when an object is created, and
 performs useful initialization tasks such as setting attributes to sensible
starting values or
 creating other objects needed by this object.

 A constructor is declared in the same way as other operations, but has the
same name as the class.
 We can manually call the constructor
 But its main purpose is to be called automatically when an object is
created.
 In PHP 5 and later, constructors are named __construct().
Classes in PHP…
class car
{
function car($param)
{
echo “Constructor called with parameter $param <br>”;
}
function __construct()
{
echo “another constructor”;
}
}
Classes in PHP…
Instantiation of Class
 After we have declared a class, we need to create an object to
work with
 Object is a particular individual that is a member of the class.
 This is also known as creating an instance or instantiating a
class.
 We create an object using the new keyword.
 We need to specify what class our object will be an instance of,
and provide any parameters required by our constructor.
Classes in PHP…
class person
{
var $name;
function person($param)
{
echo “Constructor called with parameter $param <br>”;
}
}
$a = new person(“First”); //instantiation
$b = new person(“Second”); //another instantiation
$c = new person(); //yet another instantiation

 To access a class method or property, we must use the “ ” operator.


 The keyword “this” tells PHP that the property or method belongs to
<?php
class automobile
{
var $color; //the color of the car
var $max_speed; //the maximum speed
var $price; //the price of the car, in dollars
function is_cheap()
{
$this->display();
return ($this->price < 5000); //returns TRUE if the price is smaller than 5000
}
function display()
{
echo "The price is $this->price<br>";
}
function automobile()
{
}
}

$carobject = new automobile();


$carobject->color = "red";
$carobject->price = 6000;

$cheap = $carobject->is_cheap(); //call is_cheap() method of the class


if($cheap)
print "This car is cheap!";
else
Classes in PHP…
 Making Properties and Methods Private
 Properties and methods can be public or private.

 Public means that methods or properties inside the class can be accessed

by the script that is using the class or from another class.


 For example, the following class has a public attribute and a public method

as shown:
class Car
{
var $gas = 0;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “$amount gallons added to gas tank”;
}
Classes in PHP…
 You can prevent access to properties by making them private.
 PHP provides two options for making properties and methods private,
as follows:
 private: No access from outside the class.
 protected: No access from outside except from a class inherits current class.

 Example:
class Car {
private $gas = 0;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “$amount gallons added to gas tank”;
}
Classes in PHP…
 In the following code, line 2 and 3 generates error because
$gas is private:
$mycar = new Car();
$gas_amount = $mycar->gas;
$mycar->gas = 20;
Classes in PHP…
Implementing Inheritance in PHP
 If our class is to be a subclass of another, you can use the extends keyword to specify this.
class A
{
var $attribute1;
function operation1()
{
//code here
}
}
class B extends A
{
var $attribute2;
function operation2()
{
//code here
}
Classes in PHP…
 All the following accesses to operations and attributes of an object of
type B would be valid:
$b = new B();
$b->operation1();
$b->attribute1 = 10;
$b->operation2();
$b->attribute2 = 10;

 Because class B extends class A, we can refer to operation1() and


$attribute1that were declared in class A.
 As a subclass of A, B inherits all the functionality and data.
 In addition, B has declared an attribute and an operation of its own.

You might also like