Internet Programming : CSC2233
Sessions and Cookies
H.D Supuni Shashikala
Outline
Cookies
• Introduction
• Create, Retrieve, Delete Cookie
Sessions
• Introduction
• Starting, Storing, Destroying Sessions
Sessions and Cookies
We have tried passing data to the server.But how does the server know from which
user, which requests are received ?
Noticed this ?
Persistence
▪ Persistence is the ability of data to outlive the execution of the program that
created them.
▪ An obvious way of achieving persistence is to simply save the data in a file
Why persistence ?
Ex. Counting the number of “hits” on a website i.e. how many times does a client
load your web page source
The questionnaire on computing experience
Somehow your .php needs to remember previous instances of it being requested by a
client
Persistence is the ability of data to outlive the execution of the program that created
them
HTTP and Persistence
▪ HTTP is a stateless protocol i.e the web server does not know (or care) whether 2
requests comes from the same user or not.
▪ It just handles each request without regard to the context in which it happens.
▪ 2 ways to achieve persistence:
▪ -PHP Cookies
▪ -PHP Sessions
Sessions and Cookies
Sessions and Cookies
Cookies
Cookies
▪ Cookies are used to maintain the state in between requests - even when they
occur at large time intervals from each other.
▪ Cookies allow applications to store a small amount of textual data (typically 4-
6KB) on a web client browser.
▪ Cookies are transferred between server and client according to http.
▪ PHP supports http cookies
▪ Cookies can also be thought of as tickets used to identify clients and their orders
▪ The page requested that follow personalized based on the set preferences in the
cookies
▪ Cookies can also be removed by the user at any time, so don't use them to store
a n y t h i ng tooim portant
Departm e nt o f Com p ute r Sc ienc e
[email protected]Cookies
Types of Cookies
Session cookie
▪ Also called a transient cookie, a cookie that is erased when you close the Web
browser.
▪ The session cookie is stored in temporary memory and is not retained after the
browser is closed.
▪ Session cookies do not collect information from your computer.
▪ They typically will store information in the form of a session identification that
does not personally identify the user
Types of Cookies
Persistent cookie
▪ Also called a permanent cookie, or a stored cookie, a cookie that is stored on
your hard drive until it expires (persistent cookies are set with expiration dates)
or until you delete the cookie.
▪ Persistent cookies are used to collect identifying information about the user, such
as Web surfing behavior or user preferences for a specific Web site.
Cookie Implementation
When are cookies created ?
▪ - When a new webpage is loaded ex. After a SUBMIT button the data handling
page will store the value in a cookie
If user has disabled cookies ?
▪ - Write operation will fail
▪ - Subsequent sites that rely on the cookie may have to take a default action
▪ Cookies are sent from the server to the client via “setCookie” headers
Creating PHP Cookies(PHP header() function)
▪ Cookies can be set by directly manipulating the HTTP header using the PHP
header() function
<?php
header(“Set-Cookie: user=$_POST[email]; expires=Tue, 17-May-12 14:39:58
GMT;path=/; domain=yourdomain.com”);
?>
Department of Computer Science
[email protected]Try
1. Create a simple program that allows us to store the username in a cookie that
expired after 10 seconds
2. setcookie(‘age’,’20’,time()+60*60*24*30)
3. setcookie(‘age’,’20’,0,’/’)
Source : https://www.dummies.com/
1.
<?php
setcookie("username", "CaptainAmerica", time() + 10);
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Cookie Test</title>
</head>
<body>
<h1>Trying to set a cookie</h1>
</body>
</html>
Department of Computer Science
[email protected]2. – sets cookie called age containing data 20
- Available to all pages in the same directory or subdirectory
- Expire and deleted after 30 days
3. - sets cookie called age containing data 20
- Available within entire domain that set it
- Will expire and delete when browser is closed
Uses of Cookies
User identification:
▪ Once a user visits a webpage, using cookies, that user can be remembered. And
later on, depending upon the search/visit pattern of the user, content which the
user likely to be visited are served.
▪ A good example of this is 'Retargetting'. A concept used in online marketing,
where depending upon the user's choice of content, advertisements of the
relevant product, which the user may buy, are served.
Uses of Cookies
Session management:
▪ Cookies are widely used to manage user sessions.
▪ For example, when you use an online shopping cart, you keep adding items in the
cart and finally when you checkout, all of those items are added to the list of
items you have purchased.
▪ This can be achieved using cookies
Uses of Cookies
Tracking / Analytics:
▪ Cookies are used to track the user . Which, in turn, is used to analyze and serve
various kind of data of great value, like location, technologies (e.g. browser, OS)
form where the user visited, how long (s)he stayed on various pages etc.
Uses of Cookies
Personalizing the user experience
▪ This is achieved by allowing users to select their preferences.
▪ The page requested that follow are personalized based on the set preferences in
the cookies.
Super global Variables
Superglobals are built-in variables that are always available in all scopes. There is no
need to do global $variable; to access them within functions.
▪ $_SERVER –stores data about the currently running server.
▪ $_ENV –stores data about the current client's environment.
▪ $_GET –stores data sent to the server using HTTP method GET.
▪ $_POST –stores data sent to the server using HTTP method POST.
▪ $_COOKIE –stores data contained in cookies on the client's computer.
▪ $_SESSION –used by PHP to stores data pertaining to a the server's session with a
client.
Retrieve Cookie
▪ When a Web browser accepts a cookie, you can't extract its value until the next HTTP request is
made.
▪ Ex: if you set a cookie called name with a value of Julie on page 1, you can't extract that value
until the user reaches page 2 (or page 5 or page 28—just some other page that isn't the page on
which the cookie is initially set).
▪ When a Web browser accepts a cookie, you can't extract its value until the next HTTP request is
made.
▪ Ex: if you set a cookie called name with a value of Julie on page 1, you can't extract that value
until the user reaches page 2 (or page 5 or page 28—just some other page that isn't the page on
which the cookie is initially set).
Read Specific Cookies
Alter Cookies
Delete Cookie
▪ To destroy the cookie, simply use set cookie again, only set the expiration date to
be in the past
Cookie Limitations
▪ Browsers are not required to retain more than a total of 300 cookies
▪ Browsers are required to retain no more than 20 cookies for a single domain
▪ Cookies cannot contain more than 4K of Data
▪ Clients can also switch off Cookies on their browsers
Sessions
Sessions
▪ A session is a way to store information (in the form of variables) to be used across
multiple pages.
▪ You can store user information (e.g. username, items selected, etc.) in the server
side for later use using PHP session.
▪ 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
Session Identifier
• A large, random number that we place in a browser cookie the first time we encounter
a browser
• This number is used to pick from the many sessions that the server has active at any
one time.
• Server software stores data in the session that it wants to have from one request to
another from the same browser.
• Shopping cart or login information is stored in the session in the server.
Initialize a Session
▪ We can establish/initialize a PHP session by calling session_start() before any
output has come out.
▪ It has no parameters, but informs the server that sessions are going to be used
▪ If the user has cookies set, we can use the array $_Session to store data from one
request to the next with a particular browser
Initialize a Session
▪ When you call session_start(), PHP will check to see whether the visitor sent a
session,
if it did, PHP will load the session data.
Otherwise, PHP will create a new session file on the server, and send an ID back
to the visitor to associate the visitor with the new file
Session Tracking
▪ You can create a unique session ID for your session by calling the function
session_start().
▪ Subsequent calls to session_start() retrieves the $_SESSION superglobal array.
▪ $_SESSION array contains key-value pairs that were created by the script during
the session.
Department of Computer Science
[email protected]Department of Computer Science
[email protected]Overwrite a session variable
Session Logout
▪ To logout the user we can just unset his login in the session
variable.
▪ unset($_SESSION['login']);
Removing Session Data
▪ To remove all global session variables and destroy the session, use session_unset()
and session_destroy().
▪ unset() function is used to free the specified session variable
▪ Completely destroy the session by calling the session_destroy() function.
session_destroy() reset your session and you will lose all your stored session data
How it works
▪ When session_start() is called, PHP will automatically look for a session id key in
the $_COOKIE.
▪ If session_start() is being called the first time, then no session id exists.
▪ A session id will be created; it looks something like:
af48de0c4d61b0a4f49ed8c08d1e8dad
▪ A cookie is sent to the client's computer that looks like:
PHPSESSID=af48de0c4d61b0a4f49ed8c08d1e8dad
How it works
▪ Recall that cookie created on one domain and path e.g. mydomain.com/mypath
will be available to all web pages that reside in the same domain and path.
▪ When we go from one PHP page to another the cookies that are created are
available to all the other pages in the same domain and path.
▪ So as we move to another PHP page, $_COOKIE on that page will contain the
cookie: PHPSESSID=af48de0c4d61b0a4f49ed8c08d1e8dad
How it works
▪ So on subsequent calls to session_start() $_COOKIE already contains the session id
and so PHP knows that we do not need to create a new session id.
▪ When session_start() is first called a super global array $_SESSION is created.
▪ PHP script may then use the $_SESSION array to write any data it wishes.
▪ On subsequent calls to session_start() the $_SESSION array is retrieved and it
contains all the previously stored data.
THANK YOU