SLIDE 1
Chapter 12 COOKIES AND SESSIONS INTRO Unlike the unified single - - PowerPoint PPT Presentation
Chapter 12 COOKIES AND SESSIONS INTRO Unlike the unified single - - PowerPoint PPT Presentation
Chapter 12 COOKIES AND SESSIONS INTRO Unlike the unified single process that is the typical desktop application, a web application consists of a series of disconnected HTTP requests to a web server where each request for a server page is
SLIDE 2
SLIDE 3
INTRO
SLIDE 4
INTRO
- HTTP is a stateless technology
- Each page rendered by a browser is unrelated to other pages
– even if they are from the same website
- There is no way with just HTTP to track users, create
shopping carts, or personalize web pages
- Maintaining state requires data to be sent from one page to
another
- Tools to maintain state:
- Query strings
- Form fields
- Cookies
- Sessions
SLIDE 5
THE OPTIONS
1) QUERY STRINGS
Example: <input type="hidden" name="image" value="$image"> Use $_GET or $_POST Storage is also temporary This will be discussed later
2) HIDDEN FORM FIELDS
Example: <a href="http:// …gallery.php?image=monk.jpg"> Creates $_GET variables that the next page can use Storage is temporary
SLIDE 6
THE OPTIONS
3) COOKIES
- Store data in the user's
browser
- May be disabled or
deleted by the user
- Can be made to last
longer
4) SESSIONS
- Store data on the server
itself
- More secure
- More robust (can store
more data)
SLIDE 7
COOKIES
Cookies are name/value pairs sent by a server to store information on the client's machine. Examples of cookies
- user_id=87
- email=jsmith@hotmail.com
- userName=jsmith
- passwordCookie=opensesame
- PHPSESSID=D1F15245171203E8670487F020544490
Cookies must be sent from the server to the client before any other HTML is sent.
SLIDE 8
COOKIES
Cookies aren’t harmful by themselves:
- Cookies don’t transmit viruses or steal passwords
- Contain plain text – not able to directly modify a user’s computer,
generate spam, steal files, etc.
- Misuse is generally from advertisers who want to track sites users
have visited
Typical uses:
- To allow users to skip login and registration forms
- To customize pages
- To focus advertising (banner-ads)
SLIDE 9
HOW COOKIES WORK
- On the server, a web application creates a cookie and sends
it to the browser.
- On the client, the browser saves the cookie locally and sends
it back to the server every time it accesses a page from that server.
- By default, cookies only last until the user closes his or her
web browser. However, cookies can be set to persist in the user’s browser for up to three years.
- Some users disable cookies in their browsers.
- Browsers generally accept only 20 cookies from each site
and 300 cookies total.
- Browsers can also limit each cookie to 4 kilobytes.
SLIDE 10
HOW COOKIES ARE HANDLED
SLIDE 11
THE SETCOOKIE() FUNCTION
Cookies are sent via the setcookie() function: setcookie(name, value); setcookie('name', 'Nicole');
The cookie as seen in Chrome's Developer Tools
SLIDE 12
SETCOOKIE() OPTIONAL PARAMETERS
setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly]) The setcookie parameter $expire :
- default = 0; lasts until user closes browser window;
a per-session cookie.
- other timestamp values are called persistent cookies.
- time in seconds since 1/1/70 (Unix epoch)
- or relative to the present using time()
setcookie (name, value, time()+1800);
SLIDE 13
SETCOOKIE() OPTIONAL PARAMETERS
setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly]) The setcookie parameter $path:
- the path on the server the cookie is available to
- if set to '/', the cookie is available to all directories
- n the current server
- default is the current directory (that set the cookie)
SLIDE 14
SETCOOKIE() OPTIONAL PARAMETERS
setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly])
The setcookie parameter $domain:
- the specific domain the cookie is available to
- '.example.com' makes the cookie visible within
www.example.com
- default is the name of the server that is setting
the cookie
SLIDE 15
SETCOOKIE() OPTIONAL PARAMETERS
setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly])
Other optional parameters: $secure:
- 1 means the cookie is available only if being sent using
HTTPS
- default is 0
$httponly:
- 1 means the cookie is only available through HTTP/HTTPS
and not through client-side scripts
- default is 0
SLIDE 16
SETCOOKIE() EXAMPLE
setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly])
Setting a cookie in the browser:
$name = 'userid'; $value = 'bsmith'; $expire = time()+60*60*24*30; //in seconds $path = '/'; setcookie($name, $value, $expire, $path);
SLIDE 17
ACCESSING COOKIES
To retrieve a value from a cookie that has been sent, use the suberglobal variable $_COOKIE[ ]
setcookie ('userName', 'Smitherman'); can be referred to with:
$_COOKIE['userName']
but only from another page!
SLIDE 18
DELETING A COOKIE
Cookies will automatically expire:
- when the user closes the browser
- when the expiration date/time is met
A script can manually delete cookies by:
- resetting the value parameter to ' '
- setting an expiration date in the past
SLIDE 19
MORE ABOUT COOKIES
- After a cookie is set, it isn't available until either
the page is reloaded or another page is accessed.
- After a cookie is deleted, it exists until either the
page is reloaded or another page has been accessed.
SLIDE 20
VIEWING COOKIES ON YOUR MACHINE
In Firefox: Options -> Privacy & Security -> Cookies & Site Data -> Manage Data In Chrome: Settings -> Privacy & Security -> Site Data -> Cookies and site data -> See all cookies and site data
SLIDE 21
SESSIONS
Data generated by the server and stored on the server To start a session or resume a previous session: session_start(); This must be called before any HTML is sent back to the browser! The function will try to send a cookie called PHPSESSID and a value to the browser
SLIDE 22
SESSIONS
Once the session starts, the superglobal $_SESSION[ ] array can be used to store data on the server: $_SESSION['user'] = $userID; Or to retrieve data from the server: $first_name = $_SESSION['first_name'];
SLIDE 23
SESSIONS
- Any pages that attempt to use the $_SESSION[ ]
superglobal, must have sessions enabled with session_start();
- session_start(); will try to retrieve the PHPSESSID
value from the stored cookie, or it will create a new session
- If a new session is started, any previous session
data is no longer available.
SLIDE 24
SESSIONS…UNLIKE COOKIES
- Session variables are available as soon as they
are enabled
- A session variable can be assigned a value and
then referred to from within the same script (without reloading the page.)
SLIDE 25
SESSIONS
Three kinds of information are stored:
- 1. The session identifier, PHPSESSID, is stored
as a cookie by default
- 2. The session data which is stored as a text file
- n the server
- 3. The $_SESSION array, which is how the script
accesses the data in the text file
SLIDE 26
CONTROLLING THE SESSION COOKIE
To control the session cookie, use the function: session_set_cookie_params($lifetime[, $path, $domain, $secure, $httponly]) $lifetime: of the cookie in seconds; required parameter $path: the sever path that the cookie is available to; default is current directory of the script setting the cookie. The other three parameters don’t usually need to be changed.
SLIDE 27
CONTROLLING THE SESSION COOKIE
Start a session with custom cookie parameters:
$lifetime = 60 * 60 * 24 * 365; // 1 year in seconds session_set_cookie_params($lifetime, '/'); session_start(); Note: this must occur before any HTML code is returned and session_set_cookie_params() must precede
session_start();
SLIDE 28
DELETING SESSION VARIABLES
- 1. Access the existing session using session_start();
- 2. Reset the $_SESSION array to be empty:
$_SESSION=array();
- 3. Use session_destroy(); to remove session data from
server
- 4. Specify that the session cookie expires.
**NOTE: Although there is an unset() function, don’t use it on the entire $_SESSION array, as it causes unpredictable results.
SLIDE 29
A LOGIN PAGE
- 1. A form submits the login data
- 2. A script validates and confirms that the necessary
information was submitted
- 3. A database query compares the submitted
information against the stored information
- 4. Cookies or sessions store data that reflect a
successful login
- 5. The cookie or session will check the login status so
the user won't have to login on each new page
SLIDE 30
THE LOGIN PROCESS
Login Form Validate Form Input Query Database Set Cookies and/or Start Session
OK Valid Login Incomplete Invalid login
SLIDE 31
THEN WHAT?
- Once the Login is successful, go to a default
page for logged in users: logged_in.php
- What if a user gets to logged_in.php by typing
the URL?
- Check to see if there is an existing session
with session data.
SLIDE 32
if (….) { // Login successful // Set the cookies: setcookie ('user_id', $user_id); setcookie ('first_name', $first_name); // Redirect: to logged_in.php page } In general, don't store a primary key in a cookie, because cookies can be changed.
SETTING COOKIES FOLLOWING SUCCESSFUL LOGIN
You select what cookies
- r session data you
want to store
SLIDE 33
REDIRECTING THE BROWSER
We have seen how the action attribute of a form "redirects" the browser to another page. (HTML hyperlinks do this too.) What if you don't have a form or don't want the user to click a hyperlink, and want to direct the browser to another page?
- Use PHP's header() function
- Not to be confused with:
- HTML5 <header> element
- HTML <head> element
- HTML heading elements: <h1>, <h2>, etc.
SLIDE 34
REDIRECTING
- Depending on whether or not a user has successfully
logged in, the code should redirect to the appropriate page.
- Redirection uses the header() function with the
'Location: ' string: header('Location: logged_in.php');
- This line will send to the browser a different page to
display.
- It is a server-initiated response
SLIDE 35
HEADER('LOCATION: URL')
However, to maximize browser compatibility, this is one time you want to use an absolute URL: header('Location: http://satoshi.cis.uncw.edu/~…/…logged_in.php');
SLIDE 36
DEFINING A URL DYNAMICALLY
Better yet, instead of hard-coding it, determine it dynamically. The $_SERVER superglobal array contains several values set by the web server. The relevant ones here are: $_SERVER['HTTP_HOST'] which gives the host name $_SERVER['PHP_SELF'] which refers to the current script including its directory name
SLIDE 37
EXAMPLES
The URL:
https://satoshi.cis.uncw.edu/~mferner/CSC465/buildURL.php
$_SERVER['HTTP_HOST'] is: satoshi.cis.uncw.edu $_SERVER['PHP_SELF'] could be: /~mferner/CSC465/buildURL.php dirname($_SERVER['PHP_SELF']) /~mferner/CSC465 The dirname() function returns the directory path of the parent.
SLIDE 38
EXAMPLES
The dirname() function may return a string with ending characters such as / . \ (Windows) In case of an ending character, apply the rtrim() function
Statement Returns
echo dirname("/etc/passwd") /etc echo dirname("/etc/") / or \ on Windows echo dirname(".") . echo dirname("C:\\") C:\ echo dirname("/usr/local/lib", 2); (PHP 7.0+) /usr
SLIDE 39
EXAMPLES
The URL:
https://satoshi.cis.uncw.edu/~mferner/CSC465/buildURL.php
$_SERVER['HTTP_HOST'] satoshi.cis.uncw.edu $_SERVER['PHP_SELF'] /~mferner/CSC465/buildURL.php dirname($_SERVER['PHP_SELF']) /~mferner/CSC465
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); $url = rtrim($url, '/\\.'); http://satoshi.cis.uncw.edu/~mferner/CSC465 $url .= '/logged_in.php'; // Add the page name to get:
http://satoshi.cis.uncw.edu/~mferner/CSC465/logged_in.php
Remember the concatenating assignment
- perator?
SLIDE 40
FUNCTION WITH DEFAULT VALUE
function redirect_user ($page = 'index.php') {
// URL is http:// plus the host name plus the current directory:
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
//Remove any trailing slashes (/ or \ or dot but escape \ )
$url = rtrim($url, '/\\.'); $url .= '/' . $page; // Add the page name or index.php as default header("Location: $url"); // Redirect the user: exit(); // Quit the script. } // End of redirect_user() function.
SLIDE 41
SESSION SECURITY
Never store sensitive data in a cookie Prevent session vulnerabilities: Session hijacking Session fixation Use a secure connection (https) when dealing with sensitive data. This will be covered in the next chapter.
SLIDE 42
SESSION SECURITY
Session Hijacking
- Occurs when the session ID is discovered
- If the session ID is not stored in a cookie, it
must be transmitted another way making it vulnerable
- It can then be used to access another user's
data
SLIDE 43
SESSION SECURITY
Preventing Session Hijacking
- Require the use of cookies
- Store an additional user-identifier for each user e.g.
$_SERVER['HTTP_USER_AGENT'] could be assigned to $_SESSION['agent']
- $_SERVER['HTTP_USER_AGENT'] is a string
containing browser and operating system data
- A hijack could only occur if the hijacker has the
exact same OS and browser version
SLIDE 44
SESSION SECURITY
Session Fixation
- An attacker explicitly sets the session identifier of a
session for a user
- The victim then uses the attackers session
unknowingly and inadvertently exposes sensitive data
- It can be done via URL by sending:
http://www.example.com/index...?session_name=sessionid
- Or with a redirect:
header('Location: http://host/index.php?PHPSESSID=1234');
SLIDE 45
SESSION SECURITY
Preventing Session Fixation
- Change the session ID after a user logs in
using: session_regenerate_id();
- Learn more online