CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a...

32
CHAPTER 12 COOKIES AND SESSIONS

Transcript of CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a...

CHAPTER 12

COOKIES AND SESSIONS

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

Tools:

• Hidden form fields• Query strings• Cookies• Sessions

THE OPTIONS

HIDDEN FORM FIELDS

Example:

<input type="hidden" name="userID" value="$userID">

Use $_GET or $_POST

State data is temporarily stored.

QUERY STRINGSExample:

<a href="http:// ……target_page.php?firstName=X&lastName=Y>

Creates $_GET variables that the next page can use.

Storage is also temporary

THE OPTIONS

COOKIES

• Store data in the user's Web browser

• May be disabled or deleted by the user

• Can be made to last longer

SESSIONS

• Store data on the server itself

• More secure

• More robust (can store more data)

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

USING COOKIES

Cookies are files sent by a server to store information on the user's machine.

Examples of cookies

PHPSESSID=D1F15245171203E8670487F020544490

user_id=87

[email protected]

userName=jsmith

passwordCookie=opensesame

To use cookies, they must be sent from the server to the client before any other HTML is sent.

HOW COOKIES WORK• A cookie is a name/value pair that is stored in a browser.

• On the server, a web application creates a cookie and sends it to the browser.

• On the client, the browser saves the cookie 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.

THE SETCOOKIE FUNCTION

setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly])

Setting a cookie in the browser:

$name = 'userid';

$value = 'rharris';

$expire = time()+60*60*24*30;

$path = '/';

setcookie($name, $value, $expire, $path);

 

SETCOOKIE 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 persistent cookies.• time in seconds since 1/1/70• or relative to the present using time()• 30 minutes = 1800 seconds

setcookie (name, value, time()+1800);

SETCOOKIE 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 on the current server

• default is the current directory (that set the cookie)

SETCOOKIE PARAMETERS

setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly])

The setcookie parameter $host:

• 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

SETCOOKIE PARAMETERS

setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly])

The setcookie 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

THE LOGIN PROCESS

Login Form

Validate Form Input

Query Database

Set Cookies or Start Session

OK

Valid Login

Incomplete

Invalid login

SETTING COOKIES AFTER A SUCCESSFUL LOGIN

if (….) { // Login successful

// Set the cookies:

setcookie ('user_id', $data['user_id']);

setcookie ('first_name', $data['first_name']);

// Redirect:

redirect_user('logged_in.php'); }

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.

Best practice is to use an absolute URL here: http://...

header('Location: http://webdev.cislabs.uncw.edu/~mferner/Ch12/logged_in.php');

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

DEFINING A URL DYNAMICALLY (CONT')

We also use the two functions:

• dirname() which returns just the directory i.e. /Ch12/

• rtrim() which removes spaces or the given characters

$url = 'http://'. $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

$url = rtrim($url, '/\\');

$page='index.php';

$url .= '/' . $page;

DEFINING A URL DYNAMICALLY (CONT')

The finish with:

header("Location: $url");

exit(); //don't process remaining script

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 as:

$_COOKIE['userName']

but only from another page!

TESTING THE COOKIE VALUES<?php # Script 12.4 - logged_in.php

// The user is redirected here from login.php.

// If no cookie is present, redirect the user:

if (!isset($_COOKIE['user_id'])) {

//redirect to index or login page

}

// Set the page title and include the HTML header:

$page_title = 'Logged In!';

include ('../includes/header.php');

// Print a customized message:

echo "<h1>Logged In!</h1>

<p>You are now logged in, ".$_COOKIE['first_name']."!</p>

<p><a href=\"logout.php\">Logout</a></p>";

include ('includes/footer.html');

?>

DELETING A COOKIE

Cookies will automatically expire: • when the user's browser closes

• when the expiration date/time is met

Cookies can be manually deleted by:• resetting the value parameter to ''

• setting an expiration date in the past

THINGS TO REMEMBER 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.

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.

SESSIONS

Once the session starts, the superglobal $_SESSION[ ] array can be used:

$_SESSION['user_id'] = $data['user_id'];

$_SESSION['first_name'] = $data['first_name'];

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 will no longer be available.

SESSIONS

Session variables are available as soon as they are enabled (unlike cookies.)

A session variable can be assigned a value and then referred to from within the same script (without reloading.)

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 on the server

3. The $_SESSION array, which is how the script accessed the data in the text file

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.

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();

CONTROLLING THE SESSION COOKIE

The global $_SESSION variable: an associative array that stores the data for the session.

How to set and get scalar variables:

Set a variable in a session

$_SESSION['product_code'] = 'MBT-1753';

Get a variable from a session

$product_code = $_SESSION['product_code'];

DELETING SESSION VARIABLES

1. Access the existing session using session_start();

2. Reset the $_SESSION array

3. Use destroy_session(); to remove session data from server

4. Specify that the session cookie expires.

**NOTE: There is an unset() function, but don’t use it on the entire $_SESSION array, as it causes unpredictable results.