0% found this document useful (0 votes)
51 views26 pages

PHP - Chapter 5 - Cookies and Sessions

Uploaded by

Fanta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views26 pages

PHP - Chapter 5 - Cookies and Sessions

Uploaded by

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

Chapter 5

Sessions and Cookies


management in PHP
Contents:
Describe the stateless model
What are cookies?
Create and use cookies.
 Create and Read data from Cookies
Add Parameters to a Cookie
Delete a Cookie
Explain the concepts of maintaining state with sessions
What are sessions?
Create and use sessions.
 Create and Read data from sessions
PuttingPHP session IDs in pages
Destroy a session
Maintain session data using Cookies
1 Sessions and Cookies management i
n PHP
Introduction
 Stateless Model:
 HTTP is a stateless protocol.
 A stateless protocol does not require the server to retain
information or status about each user for the duration of
multiple requests.
 this means that after an exchange is over...
 a browser requests a resource from a server
 the web server sends the resource to the browser
 ...the connection will be closed and forgotten
 this has its advantages
 because there is nothing to be kept track of, it is relatively easy
to build web servers that are very efficient
 But also it has drawbacks
 it makes it hard to follow a user on a website
2 Sessions and Cookies management i
n PHP
Why to follow a user’s?
 It is often extremely useful to be able to follow a
user’s activities on a website so that one can for
example
 have a shopping cart
 maintain the user’s identity
 display information specifically tailored to the
individual user
 Increased ability to provide the user a richer
experience of using that website
 a fine example of a site that truly exploits the user’s
identity is Amazon, which in many ways has set the
standard in the application of user identity to provide
a rich experience
3 Sessions and Cookies management i
n PHP
Login…
 Another aspect is the ability to log into a site
with username and password
 this provides some level of security
 One gets the opportunity to have “your own”
page
 with personal things, like your own photos on
Facebook
 a personal configuration of the page
 a user identity for postings on web boards
 etc.

4 Sessions and Cookies management i


n PHP
Cont…
 Some of the scenarios do not need to know
“who” you are
 “a specific browser on a particular machine” is often
enough
 here we often talk about the temporary nature of
information

 In other situations it is useful to know “who”


people are
 one can get a more personalized experience of the
site (this helps perhaps also with loyalty)
 one can log on from different machines and have
the same user experience
5 Sessions and Cookies management i
n PHP
So what can we do?
 One can add a parameter to the URL and
remember it so that all subsequent links on the
site contain it
 but that gives ugly URLs that are difficult to maintain
(one always has to rewrite all the URLs in a document)
and are vulnerable to trivial hacks
 Since the web server can see, where a request
comes from, one could use the user’s machine
address as an ID
 but what if it is a shared computer?
 or if it just looks like one computer due to NAT or a proxy?
 It would be great if a website could save a little bit
of data on the user’s machine ...
6 Sessions and Cookies management i
n PHP
So…
 So, web applications need to track the user's
progress from page to page, for example when a
web server is required to customize the content
of a web page for a user.
 Solutions to address the above mentioned
problems are cases that include:
 the use of HTTP cookies.
 server side sessions,
 hidden variables (when the current page contains a
form), and
 URL-rewriting using URI-encoded parameters, e.g.,
/index.php?session_id=some_unique_session_code.

7 Sessions and Cookies management i


n PHP
Solution…
 HTTP remains stateless – there is no fixed connection
between web server and browser
 While the stateless nature of HTTP has some important
benefits:
 after all, maintaining state requires some overhead.
 it presents a unique challenge to developers who need to
create stateful web applications.
 With no way to identify the client, it is impossible to
determine
 whether the user is already logged in,
 has items in a shopping cart, or needs to register.
 An elegant solution to this problem, originally conceived
by Netscape, is a state management mechanism called
cookies.
8 Sessions and Cookies management i
n PHP
Cookies
 a web server can leave a “cookie” in the
browser (i.e. on the user’s computer)
 it is up to the browser to manage these cookies
 the cookie gets transmitted to the server in
future connections
 A cookie is a small piece of data (typically
max. 4 kB, usually far less) that is used by
the web server to identify the user.
 Cookies may be limited in time with an
expiration date
 else the cookie will be deleted when the browser
is closed
9 Sessions and Cookies management
in PHP
Cont…
 are an extension of the HTTP protocol.
 they consist of two HTTP headers:
 the Set-Cookie response header and
 the Cookie request header.
 When a client sends a request for a particular URL,
the server can opt to include a Set-Cookie header in
the response, so as to request for the client to include
a corresponding Cookie header in its future requests
 Cookies
 allow a unique identifier to be included in each request (in
a Cookie header),
 This help to uniquely identify clients and associate their
requests together.

10 Sessions and Cookies management i


n PHP
11 Sessions and Cookies management i
n PHP
Create Cookies in PHP
 Use setcookie() function to create a cookie.
Syntax
setcookie(string name, string value, int expire,
string path,
string domain, int secure);
Example:
<?php
// Setting a cookie
setcookie("username", “Abebe", time()
+10*24*60*60);
?>
12 Sessions and Cookies management i
n PHP
Paramet
Description
er
name The name of the cookie.
value The value of the cookie.
The expiry date in UNIX timestamp format.
This implies, After this time cookie will become
expires
inaccessible.
The default value is 0.
Specify the path on the server for which the
cookie will be available.
path
If set to '/', the cookie will be available within the
entire domain.
Specify the domain for which the cookie is
domain available to
e.g www.example.com.
This field, if present, indicates that the cookie
should be sent only if a secure HTTPS connection
secure
13 exists.
Sessions and Cookies management i
n PHP
Accessing cookie
 The PHP $_COOKIE super global variable is
used to retrieve a cookie value.
<html>
<head><title>sample on cookie</title></head>
<body>
<?php
if(!isset($_COOKIE["username"]))
{

setcookie("username", "Abebe", time()+10*24*60*60);


}
else{
echo $_COOKIE["username"]; // used to access a
cookie
}?>
</body>
14 </html> Sessions and Cookies management i
n PHP
Check if Cookies are Enabled

 count the $_COOKIE array variable


<?php
setcookie("username", "Abebe", time()+10*24*60*60);
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
15 Sessions and Cookies management i
n PHP
Removing Cookies
Cookies can be deleted by calling the
setcookie() function with the cookie name and
any value (such as an empty string) with
expiration date set in the past,
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>

16 Sessions and Cookies management i


n PHP
Scope of cookies
 Cookies can only be read from the site from
which they were set
 this helps to ensure that one can not steal
cookies (and thus identities) through hostile
websites

17 Sessions and Cookies management i


n PHP
Cookies and their use
 Shopping cart
 when the front page appears, set a new (empty) cookie
 items are added by updating the cookie
 alternatively, one can store goods in the server’s database
and just store an ID in the cookie that points to your
basket
 Login
 user inputs name and password into a form
 after the combination has been verified, it sends a cookie
to the user that identifies the user to the system
 next time the user visits the page, the web server checks
if there is a cookie, and if so the user is identified

18 Sessions and Cookies management i


n PHP
Criticism of cookies

 One can not be completely anonymous on the


net
 most ads/banners come from relatively few
advertisers.
 these may, with the help of cookies, follow a
browser/ computer combination on all the sites they
advertise on.
 there have been examples of security
vulnerabilities in browsers, so that adversaries
can get access to cookies
 which they can use to gain access to sites with a
faked identity
19 Sessions and Cookies management i
n PHP
Sessions
 A combination of cookies and data stored on
the server (automatically by PHP)
 saves a cookie containing an ID on the user’s
computer that points to a session on the server
 A session is a global PHP array ($_SESSION)
 A session is designed as an easy way to store
data – for a short period
 a session’s lifetime in PHP is only 24 minutes by
default

20 Sessions and Cookies management i


n PHP
Starting PHP session
 Sessions must be started at the top of the
page before it is used.
session_start()
 Session_start() function creates a new session
and generate a unique session ID for the
user.
 it first checks for an existing session ID. If it finds
one, i.e. if the session is already started, it sets
up the session variables and if doesn't, it starts a
new session by creating a new session ID.

21 Sessions and Cookies management i


n PHP
Storing and Accessing Session Data
 session data can be stored as key-value pairs in the
$_SESSION[] super global array.
 The stored data can be accessed during lifetime of a session.

<?php
// Starting session
session_start();

// Storing session data


$_SESSION["firstname"] = “Abebe";
$_SESSION["lastname"] = “Lemlem";
?>

22 Sessions and Cookies management i


n PHP
Accessing session data
 We can access the session data we set on our
previous example from any other page on the
same web domain
 Simply recreate the session by calling
session_start() and then pass the corresponding
key to the $_SESSION associative array.
<?php
session_start();
echo $_SESSION["Name"];
?>

23 Sessions and Cookies management i


n PHP
Destroying PHP session
 all global session variables can be removed by
destroing the session using
 session_unset(“sessionId”) //remove all session
variables
 session_destroy():// destroy the session
<?php
session_start(); <?php
// Removing session data session_start();
if(isset($_SESSION[“username"])){ // Destroying session
session_unset($_SESSION[“usernam session_destroy();
e"]);
?>
}
?>

24 Sessions and Cookies management i


n PHP
Session for login
 Sessions are tied to an individual user and a
corresponding browser
 therefore, they are well suited to handle logins
 Useful command in this context: header()
 header() is used to send HTTP headers to the
browser
 as other header information (such as cookies and
sessions), such a command should precede any
HTML in a PHP file
 a particularly interesting header in this context is
Location:, which redirects the browser to
another URL
25 Sessions and Cookies management i
n PHP
Question ’

?
26 Sessions and Cookies management i
n PHP

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy