Vous êtes sur la page 1sur 30

CSE 301

COOKIES + SESSIONS + WEB CACHE


Including files: include
include("filename"); PHP
include("header.html");
include("shared-code.php"); PHP

• inserts the entire contents of the given file into the PHP script's output page
• encourages modularity
• useful for defining reused functions needed by multiple pages
Including a common HTML file
<!DOCTYPE html>
<!-- this is top.html -->
<html><head><title>This is some common code</title>
... HTML

include("top.html"); # this PHP file re-uses top.html's HTML content

• Including a .html file injects that HTML output into your PHP page at that
point

• useful if you have shared regions of pure HTML tags that don't contain any
PHP content
Including a common PHP file
<?php
# this is common.php
function useful($x) { return $x * $x; }
function top() {
?>
<!DOCTYPE html>
<html><head><title>This is some common code</title>
...
<?php
} PHP
include("common.php"); # this PHP file re-uses common.php's PHP code
$y = useful(42); # call a shared function
top(); # produce HTML output
...
• including a .php file injects that PHP code into your PHP file at that point
• if the included PHP file contains functions, you can call them
What is a cookie?
• cookie: a small amount of information sent by a
server to a browser, and then sent back by the
browser on future page requests
• cookies have many uses:
• authentication
• user tracking
• maintaining user preferences, shopping carts, etc.
• a cookie's data consists of a single name/value pair,
sent in the header of the client's HTTP GET or POST
request
How cookies are sent
• when the browser
requests a page, the server
may send back a cookie(s)
with it
• if your server has
previously sent any cookies
to the browser, the browser
will send them back on
subsequent requests
Cookies: keeping “state” (cont.)
client server

ebay 8734
usual http request msg Amazon server
cookie file creates ID
usual http response
1678 for user create backend
ebay 8734
set-cookie: 1678 entry database
amazon 1678
usual http request msg
cookie: 1678 cookie- access
specific
usual http response msg action

one week later:


access
ebay 8734 usual http request msg
amazon 1678 cookie: 1678 cookie-
specific
usual http response msg action
Application Layer 2-7
Myths about cookies
• Myths:
• Cookies are like worms/viruses and can erase data from the user's hard disk.
• Cookies are a form of spyware and can steal your personal information.
• Cookies generate popups and spam.
• Cookies are only used for advertising.
• Facts:
• Cookies are only data, not program code.
• Cookies cannot erase or read information from the user's computer.
• Cookies are usually anonymous (do not contain personal information).
• Cookies CAN be used to track your viewing habits on a particular site.
A "tracking cookie"

• an advertising company can put a cookie on your machine when you visit one
site, and see it when you visit another site that also uses that advertising
company
• therefore they can tell that the same person (you) visited both sites
• can be thwarted by telling your browser not to accept "third-party cookies"
How long does a cookie exist?
• session cookie : the default type; a temporary cookie that is stored only in the
browser's memory
• when the browser is closed, temporary cookies will be erased
• can not be used for tracking long-term information
• safer, because no programs other than the browser can access them
• persistent cookie : one that is stored in a file on the browser's computer
• can track long-term information
• potentially less secure, because users (or programs they run) can open cookie
files, see/change the cookie values, etc.
Setting a cookie in PHP
setcookie("name", "value"); PHP
setcookie("username", “allllison");
setcookie("age", 19); PHP

• setcookie causes your script to send a cookie to the user's browser


• setcookie must be called before any output statements (HTML
blocks, print, or echo)
• you can set multiple cookies (20-50) per user, each up to 3-4K bytes
• by default, the cookie expires when browser is closed (a "session cookie")
Retrieving information from a cookie
$variable = $_COOKIE["name"]; # retrieve value of the cookie
if (isset($_COOKIE["username"])) {
$username = $_COOKIE["username"];
print("Welcome back, $username.\n");
} else {
print("Never heard of you.\n");
}
print("All cookies received:\n");
print_r($_COOKIE); PHP

• any cookies sent by client are stored in $_COOKIES associative array


• use isset function to see whether a given cookie name exists
Expiration / persistent cookies
setcookie("name", "value", expiration); PHP
$expireTime = time() + 60*60*24*7; # 1 week from now
setcookie("CouponNumber", "389752", $expireTime);
setcookie("CouponValue", "100.00", $expireTime); PHP
• to set a persistent cookie, pass a third parameter for when it should expire
• indicated as an integer representing a number of seconds, often relative to current
timestamp
• if no expiration passed, cookie is a session cookie; expires when browser is closed
• time function returns the current time in seconds
• date function can convert a time in seconds to a readable date
Deleting a cookie
setcookie("name", FALSE); PHP
setcookie("CouponNumber", FALSE); PHP

• setting the cookie to FALSE erases it

• you can also set the cookie but with an expiration that is before the present
time:
setcookie("count", 42, time() - 1); PHP

• remember that the cookie will also be deleted automatically when it expires,
or can be deleted manually by the user by clearing their browser cookies
Clearing cookies in your browser
• Chrome: Wrench   → History → Clear all browsing data...
• Firefox: Firefox menu → Options → Privacy → Show Cookies... → Remove
(All) Cookies
Common cookie bugs
When you call setcookie, the cookie will be available in $_COOKIE on
the next page load, but not the current one. If you need the value during the
current page request, also store it in a variable:
setcookie("name", "joe");
print $_COOKIE["name"]; # undefined PHP
$name = "joe";
setcookie("name", $name);
print $name; # joe PHP
• setcookie must be called before your code prints any output or HTML content:
<!DOCTYPE html><html>
<?php
setcookie("name", "joe"); # should precede HTML content!
What is a session?
• session: an abstract concept to represent a series of HTTP requests and
responses between a specific Web browser and server
• HTTP doesn't support the notion of a session, but PHP does

• sessions vs. cookies:


• a cookie is data stored on the client
• a session's data is stored on the server (only 1 session per client)
• sessions are often built on top of cookies:
• the only data the client stores is a cookie holding a unique session ID
• on each page request, the client sends its session ID cookie, and the
server uses this to find and retrieve the client's session data
How sessions are established
• client's browser makes an initial request
to the server
• server notes client's IP address/browser,
stores some local session data, and sends
a session ID back to client (as a cookie)
• client sends that same session ID (cookie)
back to server on future requests
• server uses session ID cookie to retrieve
its data for the client's session later (like a
ticket given at a coat-check room)
Cookies vs. sessions
• duration: sessions live on until the user logs out
or closes the browser; cookies can live that long, or
until a given fixed timeout (persistent)
• data storage location: sessions store data on the
server (other than a session ID cookie); cookies
store data on the user's browser
• security: sessions are hard for malicious users to
tamper with or remove; cookies are easy
• privacy: sessions protect private information from
being seen by other users of your computer;
cookies do not
Implementing user logins
• many sites have the ability to create accounts and
log in users
• most apps have a database of user accounts
• when you try to log in, your name/pw are
compared to those in the database
Sessions in PHP: session_start
session_start(); PHP

• session_start signifies your script wants a session with the user


• must be called at the top of your script, before any HTML output is
produced
• when you call session_start:
• if the server hasn't seen this user before, a new session is created
• otherwise, existing session data is loaded into $_SESSION associative
array
• you can store data in $_SESSION and retrieve it on future pages
• complete list of PHP session functions
Accessing session data
$_SESSION["name"] = value; # store session data
$variable = $_SESSION["name"]; # read session data
if (isset($_SESSION["name"])) { # check for session data PHP
if (isset($_SESSION["points"])) {
$points = $_SESSION["points"];
print("You've earned $points points.\n");
} else {
$_SESSION["points"] = 0; # default
} PHP

• the $_SESSION associative array reads/stores all session data

• use isset function to see whether a given value is in the session


Common session bugs
• session_start doesn't just begin a session; it also reloads any existing session for
this user. So it must be called in every page that uses your session data:
# the user has a session from a previous page
print $_SESSION["name"]; # undefined

session_start();
print $_SESSION["name"]; # joe PHP
• previous sessions will linger unless you destroy them and regenerate the user's
session ID:
session_destroy();
session_start(); PHP
Ending a session
session_destroy(); PHP
• session_destroy ends your current session
• potential problem: if you call session_start again later, it sometimes
reuses the same session ID/data you used before
• if you may want to start a completely new empty session later, it is best to
flush out the old one:
session_destroy();
session_regenerate_id(TRUE); # flushes out session
#ID number
session_start(); PHP
Session timeout
• because HTTP is stateless, it is hard for the server to know when a user has
finished a session
• ideally, user explicitly logs out, but many users don't
• client deletes session cookies when browser closes
• server automatically cleans up old sessions after a period of time
• old session data consumes resources and may present a security risk
• you can explicitly delete a session by calling session_destroy
Web caches (proxy server)
• HTTP supports Proxy servers
• Proxy server
• a computer that keeps copies of responses to recent requests
• Goal: satisfy a client’s request without involving the original server

proxy
 user sets browser: Web HT
TP u est
req server req
accesses via cache H
client TTP
ues
t HT
TP
o nse
res p origin
 browser sends all HTTP p ons P res
T server
e HT
requests to cache ue
s t
eq
 object in cache: cache T Pr o ns
e
T p
H es
returns object TTP
r
H
 else cache requests
object from origin client origin
server, then returns server
object to client
Application Layer 2-26
More about Web caching
 cache acts as both why Web caching?
client and server  reduce response time for
 server for original client request
requesting client
 client to origin server  reduce traffic on an
 typically cache is institution’s access link
installed by ISP  Internet dense with
(university, company, caches: enables “poor”
residential ISP) content providers to
effectively deliver
content (so too does P2P
file sharing)

Application Layer 2-27


Caching example:
assumptions:
 avg object size: 100K bits origin
 avg request rate from browsers to servers
origin servers:15/sec public
 avg data rate to browsers: 1.50 Mbps Internet
 RTT from institutional router to any
origin server: 2 sec
 access link rate: 1.54 Mbps
1.54 Mbps
consequences: access link
 LAN utilization: 15% problem! institutional
 access link utilization = 99% network
1 Gbps LAN
 total delay = Internet delay + access
delay + LAN delay
= 2 sec + minutes + usecs

Application Layer 2-28


Consistency of Web caching
 The major issue: How to maintain consistency?
 Two ways:
 Pull
• Web caches periodically pull the web server to see if a document is modified
 Push
• Whenever a server gives a copy of a web page to a web cache, they sign a lease with an
expiration time; if the web page is modified before the lease, the server notifies the
cache

06/12/2020
Conditional GET
client server
 Goal: don’t send object if
cache has up-to-date
cached version HTTP request msg
object
If-modified-since: <date>
 no object transmission not
delay modified
HTTP response
 cache: specify date of HTTP/1.0
before
cached copy in HTTP 304 Not Modified <date>
request
If-modified-since:
<date>
 server: response contains HTTP request msg
no object if cached copy If-modified-since: <date> object
is up-to-date: modified
HTTP response after
HTTP/1.0 304 Not
HTTP/1.0 200 OK <date>
Modified
<data>
Application Layer 2-30

Vous aimerez peut-être aussi