66
SESSION AND COOKIES

First Name Last Name Please enter your logon information: John Submit Chen Web Server Login.php Web Server Hello John Chen Greetings. php Please enter

Embed Size (px)

Citation preview

SESSION AND COOKIES

WHAT IS STATE MANAGEMENT?

First Name

Last Name

Please enter your logon information:

John

SubmitSubmit

Chen

Web ServerWeb Server

Login.php Login.php

Web ServerWeb Server

Hello John Chen

Greetings. php

Please enter your logon information:

John

SubmitSubmit

Chen

Hello

Greetings. php

I forget who you are!!

I forget who you are!!

First Name

Last Name

Without State Management

With State Management

TYPES OF STATE MANAGEMENT

Server-Side State Management

Client-Side State Management

Application state Information is available to all

users of a Web application

Cookies Text file stores information to

maintain state

Session state Information is available only to a

user of a specific session

The ViewState property Retains values between multiple

requests for the same page

Database In some cases, use database

support to maintain state on your Web site

Query strings Information appended to the end of

a URL

SERVER-SIDE STATE MANAGEMENT Application state is a global

storage mechanism accessible from all pages in the Web application

Session state is limited to the current browser session Values are preserved through the use

of application and session variables Scalability

ASP.NET session is identified by the SessionID string

Web ServerWeb Server

Client ComputerClient Computer

Application and Session variables

SessionID

CLIENT-SIDE STATE MANAGEMENT Uses cookies to maintain state

Persistent cookies Temporary/ Non-persistent cookies

Less reliable than server-side state management options User can delete cookies

Less secure than server-side state management options

Limited amount of information Client-side restrictions on file sizes

Web ServerWeb Server

Client ComputerClient Computer

Cookies

APPLY TO NORMAL PHP

While the configuration in this tutorial applies to ProdigyView, the concepts apply to normal cookies and sessions in php. You may use these concepts with these two php functions.session_set_cookie_paramshttp://php.net/manual/en/function.session-set-cookie-params.php

setcookiehttp://php.net/manual/en/function.setcookie.php

SERVER SIDE INCLUDES

You can insert the content of one file into another file before the server executes it, with the require() function. The require() function is used to create functions, headers, footers, or elements that will be reused on multiple pages.

<?php require("header.htm"); ?>

HOW TO CREATE VARIABLES STORING VALUES ACROSS PHP SCRIPTS’ CALLS?

Client-server connection is not permanent=> Cannot be saved in program memory

There are many clients connecting simultaneously => Cannot be saved in file (you cannot identify clients as well sometimes)

.

.

.

DIFFERENT MECHANISMS OF THE SAME SOLUTION

Cookies Cookies are a mechanism for storing data in the

remote browser and thus tracking or identifying return users.

Sessions Session support in PHP consists of a way to

preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

WHAT IS MEANT BY STATE?

To maintain state means the ability to retain values of variables and to keep track of users who are logged into the system.

 WHY COOKIES AND SESSIONS ARE USED? HTTP is a stateless protocol. This means

that each request is handled independently of all the other requests and it means that a server or a script cannot remember if a user has been there before.

However, knowing if a user has been there before is often required and therefore something known as cookies and sessions have been implemented.

METHODS FOR MAINTAINING STATE

Cookies Sessions Passing [hidden] variables

WHAT IS A COOKIE

Cookies is data the stored in the user’s browser. Unlike sessions, cookies will last if a user closes their browser. Cookies have a size limit set by the browser. Sensitive information should not be stored in the cookie.

Stored on user’s computer

WHAT IS A COOKIE?

Cookies are simple text strings of the form of

name=value which are stored persistently on the client’s machine. A URL is stored with each cookie and it is used by the browser to determine whether it should send the cookie to the web server.

A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

SET A COOKIE

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

name = cookie name value = data to store (string) expire = UNIX timestamp when the cookie expires.

Default is that cookie expires when browser is closed. path = Path on the server within and below which the

cookie is available on. domain = Domain at which the cookie is available for. secure = If cookie should be sent over HTTPS

connection only. Default false.

HOW TO CREATE A COOKIE

The setcookie() function is used to create cookies.

Note: The setcookie() function must appear BEFORE the <html> tag.

setcookie(name, [value], [expire], [path],

[domain], [secure]);

This sets a cookie named "uname" - that expires after ten hours.

<?php setcookie("uname", $name, time()+36000); ?>

<html> <body> …

 SET A COOKIE EXAMPLES

setcookie(‘name’,’Robert’)

This command will set the cookie called name on the user’s PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire).

SET A COOKIE - EXAMPLES

setcookie(‘age’,’20’,time()+60*60*24*30)

This command will set the cookie called age on the user’s PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days.

SET A COOKIE - EXAMPLES

setcookie(‘gender’,’male’,0,’/’)

This command will set the cookie called gender on the user’s PC containing the data male. It will be available within the entire domain that set it. It will expire and be deleted when the browser is closed.

READ COOKIE DATA

All cookie data is available through the superglobal $_COOKIE:

$variable = $_COOKIE[‘cookie_name’] or $variable =

$HTTP_COOKIE_VARS[‘cookie_name’]; e.g. $age = $_COOKIE[‘age’]

HOW TO RETRIEVE A COOKIE VALUE To access a cookie you just refer to the cookie

name as a variable or use $_COOKIE array Tip: Use the isset() function to find out if a

cookie has been set.

<html> <body><?php

if (isset($uname)) echo "Welcome " . $uname . "!<br />";

else echo "You are not logged in!<br />"; ?>

</body> </html>

COOKIE EXAMPLE

<?php$count++;setCookie(“count”, $count);

?>

Welcome! You’ve seen this site

<?php print($count . ($count == 1 ? “ time!” : “ times!”)); ?>

DELETE A COOKIE

To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past…

setcookie(‘cookie_name’,’’,time()-6000)

Note that theoretically any number taken away from the time() function should do, but due to variations in local computer times, it is advisable to use a day or two.

WHAT IS PARAMETER PASSING & SESSION TRACKING?

-> Values of the text typed in user form is passed to other HTML and/or server side script is called parameter passing.-> A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application.[1]-> Maintenance of user's state during session(e.g.login to logout) is called a Session Tracking.

WAYS

Visible form parameters Hidden form parameters Cookies Session URL Rewriting

PARAMETER PASSING WITH <FORM>

Methods of passing parameters with <form>

GET (smaller data i.e.1024 bytes) POST(bigger data, as well as file

upload) PHP uses predefined variables

$_GET['varname'] $_POST['varname']

PREDEFINED VARIABLES[2]

PHP provides a large number of predefined variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers to all scripts.

Superglobals — Superglobals are built-in variables that are always available in all scopes

$GLOBALS — References all variables available in global scope

$_SERVER — Server and execution environment information $_SERVER — Server and execution environment information $_GET — HTTP GET variables $_POST — HTTP POST variables $_FILES — HTTP File Upload variables

LIST OF PREDEFINED VARIABLES [2]...

$_REQUEST — HTTP Request variables $_SESSION — Session variables $_ENV — Environment variables $_COOKIE — HTTP Cookies $php_errormsg — The previous error message $HTTP_RAW_POST_DATA — Raw POST data $http_response_header — HTTP response

headers $argc — The number of arguments passed to

script $argv — Array of arguments passed to script

THE VALUES OF PREDEFINED VARIABLES

Values of predefined variables can be seen with

<?phpphpinfo()?>

WHAT IS A SESSION?

The session support allows you to register arbitrary numbers of variables to be preserved across requests.

A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

SESSIONS

Sessions are just like cookies, except they store the user’s data on the web server. Every request has a unique session id.

Sessions are more reliable than cookies.

WHAT IS A SESSION

Sessions is information that relates to a user and is stored on the server. A session will no longer exist once the browser closes. Sessions do not have a size limit. Sensitive information should be stored in the session.

User saves session information

User retrieves session information

HOW TO CREATE A SESSION

The session_start() function is used to create cookies.

<?php session_start(); ?>

HOW TO RETRIEVE A SESSION VALUE

Register Session variable session_register('var1','var2',...); // will also create a

session PS:Session variable will be created on using even if you will not register it!

Use it<?php session_start();

if (!isset($_SESSION['count'])) $_SESSION['count'] = 0;

else $_SESSION['count']++;

?>

SESSION EXAMPLE

?php

// start the session session_start();

// Get the user's input from the form $name = $_POST['name'];

// Register session key with the value $_SESSION['name'] = $name;

?>

SESSION One of the standard examples used to demonstrate how a session

works is the hit counter application.

The example of coding:

<?php

// initialize a session session_start();

// increment a session counter $_SESSION['counter']++;

// print value echo "You have viewed this page " . $_SESSION['counter'] . " times";

?>

With above code, the counter will increases by 1 on each subsequent page load.

If two browser windows are open, and request the same page in each one, PHP will maintain and increment individual session counters for each browser instance.

EXAMPLE 1

In this example:-• Required to log in.• Then stored the login name and session start time as two

session variables.

This information is used to display the total number of minutes the session has been active.

<?php // initialize a session session_start(); ?> <html> <head></head> <body>

<?php if (!isset($_SESSION['name']) && !isset($_POST['name'])) {     // if no data, print the form ?>     <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">         <input type="text" name="name">         <input type="submit" name="submit" value="Enter your name">     </form> <?php } else if (!isset($_SESSION['name']) && isset($_POST['name'])) {     // if a session does not exist but the form has been submitted     // check to see if the form has all required values     // create a new session     if (!empty($_POST['name'])) {         $_SESSION['name'] = $_POST['name'];         $_SESSION['start'] = time();         echo "Welcome, " . $_POST['name'] . ". A new session has been activated for you. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to refresh the page.";     }     else {         echo "ERROR: Please enter your name!";     } } else if (isset($_SESSION['name'])) {     // if a previous session exists     // calculate elapsed time since session start and now     echo "Welcome back, " . $_SESSION['name'] . ". This session was activated " . round((time() - $_SESSION['start']) / 60) . " minute(s) ago. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to refresh the page."; } ?> </body> </html>

CONTINUE…

The session start time is recorded in $_SESSION['start'] with the time() function.

Then, the value stored in $_SESSION['start'] is compared with the most current value of time() to calculate and display an (approximate) display of elapsed time.

The call to session_start() must appear first, before any output is generated by the script.

This is because the PHP session handler internally uses in-memory cookies to store session data, and the cookie creation headers must be transmitted to the client browser before any output.

EXAMPLE 2

Every session has a unique session ID – used by PHP to keep track of different clients.

This session ID is a long alphanumeric string, which is automatically passed by PHP from page to page so that the continuity of the session is maintained.

Use the session_id() function, as in this simple example:

<?php

// initialize a session session_start();

// print session ID echo "I'm tracking you with session ID " . session_id();

?>

EXAMPLE 3

When the user shuts down the client browser and destroys the session, the $_SESSION array will be flushed of all session variables.

A session can also explicitly be destroy. For example, when a user logs out - by calling the

session_destroy() function. Consider the given example below:-

<?php

// initialize a session session_start();

// then destroy it session_destroy();

?>

Before calling a session_destroy() to destroy a session, session_start() is called first to recreate it.

$_SESSION is a superglobal – can use it inside and outside functions without needing to declare it as global first.

COOKIES

PHP offers a single function for cookie manipulation – setcookie().

This function allows a read and write of cookie files.

<?php

if (!isset($_COOKIE['visited'])) {     // if a cookie does not exist     // set it     setcookie("visited", "1", mktime()+86400, "/") or die("Could not set cookie");     echo "This is your first visit here today."; } else {     // if a cookie already exists     echo "Nice to see you again, old friend!"; }

?>

CONTINUE…

The setcookie() function accepts six arguments: i. name: the name of the cookieii. value: the value of the cookie iii. expires: the date and time at which the cookie expires iv. path: the top-level directory on the domain from which

cookie data can be accessed v. domain: the domain for which the cookie is valid vi. secure: a Boolean flag indicating whether the cookie should

be transmitted only over a secure HTTP connection

Cookie values are automatically sent to PHP from the client.

Then, converted to key-value pairs in the $_COOKIE variable, a superglobal array similar to $_SESSION.

Values can be retrieved using standard associative array notation.

FORM AND FUNCTION <?php

if (!isset($_POST['email'])) {     // if form has not been submitted     // display form     // if cookie already exists, pre-fill form field with cookie value ?>     <html>     <head></head>     <body>          <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">

        Enter your email address: <input type="text" name="email" value="<?php echo $_COOKIE['email']; ?>">         <input type="submit" name="submit">         <?php         // also calculate the time since the last submission         if ($_COOKIE['lastsave']) {             $days = round((time() - $_COOKIE['lastsave']) / 86400);             echo "<br /> $days day(s) since last submission";         }         ?>     </form>          </body>     </html> <?php }

CONTINUE…

else {     // if form has been submitted     // set cookies with form value and timestamp     // both cookies expire after 30 days     if (!empty($_POST['email'])) {         setcookie("email", $_POST['email'], mktime()+(86400*30), "/");         setcookie("lastsave", time(), mktime()+(86400*30), "/");         echo "Your email address has been recorded.";     }     else {         echo "ERROR: Please enter your email address!";     } } ?> </body> </html>

CONTINUE…

The value entered into the form is stored as a cookie called email.

It will automatically retrieved to pre-fill the form field on all subsequent requests.

The time at which the data was entered is stored as a second cookie, and used to calculate the time elapsed between successive entries.

SESSION TRACKING IS DONE WITH

As HTTP is stateless protocol Session Tracking must be maintained by programmers with following ways:

Hidden form parameters Cookies Session URL Rewriting

HIDDEN PARAMETER PASSING

Parameter is passed from 1 page to other which is not visible from user.

<input type=hidden name=”username” value=”amichoksi”>

Can be retrieved in PHP by $_GET[“username”] $_POST[“username”]

COOKIES [2]

Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users.

Set Cookie bool setcookie ( string $name string $value , int

$expire=0 , string $path , string $domain , bool $secure=false , bool $httponly=false)

setcookie(“username”,”ami”,time()+300);

Read Cookie $_COOKIE['name']

SESSION FUNCTIONS [2]session_cache_expire — Return current cache expiresession_cache_limiter — Get and/or set the current cache limitersession_commit — Alias of session_write_closesession_decode — Decodes session data from a stringsession_destroy — Destroys all data registered to a sessionsession_encode — Encodes the current session data as a stringsession_get_cookie_params — Get the session cookie parameterssession_id — Get and/or set the current session idsession_is_registered — Find out whether a global variable is registered in a sessionsession_module_name — Get and/or set the current session module

session_name — Get and/or set the current session namesession_regenerate_id — Update the current session id with a newly generated onesession_register — Register one or more global variables with the current sessionsession_save_path — Get and/or set the current session save pathsession_set_cookie_params — Set the session cookie parameterssession_set_save_handler — Sets user-level session storage functionssession_start — Initialize session datasession_unregister — Unregister a global variable from the current sessionsession_unset — Free all session variablessession_write_close — Write session data and end session

EXAMPLES• File: Page1.php• <?php session_start(); echo 'Welcome to page #1'; $_SESSION['favcolor'] = 'green'; $_SESSION['animal'] = 'cat'; $_SESSION['time'] = time();session_set_cookie_params(10,"/","sun.com",t

rue, false);?>

EXAMPLE...• Filename Page2.phpsession_start();echo 'Welcome to page #2<br />';echo $_SESSION['favcolor']; // greenecho $_SESSION['animal']; // catecho date('Y m d H:i:s',

$_SESSION['time']);?>• session_unset ();//releasing session

data• Echo $_SESSION['time'];//no output

URL RE-WRITING• The Apache server’s mod_rewrite

module gives the ability to transparently redirect one URL to another by modifying URL (i.e. re-writing), without the user’s knowledge.

• Used in situations:-– Pass some information to other page

– redirecting old URLs to new addresses Or

- cleaning up the ‘dirty’ URLs coming from a poor

publishing system

REQUIRED CONFIGURATION AND EXAMPLES

• Following line must be uncommented available in /etc/httpd/conf/httpd.conf file

LoadModule rewrite_module modules/mod_rewrite.so • URL Rewriting examples

– http://localhost/ami/123– http://localhost/~ami/UrlRewrite.php?name=a

michoksi

RETRIEVAL OF URL REWRITING DATA

• <?php if(isset($_SERVER['PATH_INFO'])){ echo $_SERVER['PATH_INFO'];} else if(isset($_GET['username'])) { echo $_GET['username'];} ?>

HOW TO DELETE A COOKIE

It will expireor

Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string (""), and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.

REMOVE A COOKIES

<?php

// delete cookie setcookie("lastsave", NULL, mktime() - 3600, "/");

?>

To remove a cookie from the client, setcookie() is called.

With the same syntax used to originally set the cookie, but an expiry date in the past.

This will cause the cookie to be removed from the client system.

HOW TO DELETE A SESSION VALUE session_unregister(´varname´);

How to destroy a session: session_destroy()

DESTROYING A SESSION

<?php // start the session session_start();

$_SESSION = array(); session_destroy();

if($_SESSION['name']){     print "The session is still active"; } else {     echo "Ok, the session is no longer active! <br />";     }

?>

COOKIE PATH & SESSION PATH

The cookie path and session is path on your server that you cookie or session will be accessible. Example: If you make your cookie path ‘/store/products’, the cookie will only be available on ‘http://www.example.com/store/products/index.php’.Using ‘/’ will make the cookie or session available in any directory.

COOKIE DOMAIN AND SESSION DOMAIN

The cookie and session domain is the domain the cookie/session is available on. If your domain is www.example.com, setting you’re cookie/session to that domain will make is only accessible under www.example.com. If it was set to subdomain.example.com, it will only be available under subdomain.example.com.Setting the domain to ‘.example.com’ will make the session/cookie available under all subdomains.

COOKIE SECURE & SESSION SECURE

Cookie Secure and Session Secure will ensure that your data for a session/cookie will only save over an https connection.It is up to you, the developer, to make sure the value is read only over an https connection.

COOKIE AND SESSION HTTP ONLY

In some situations, the requirement may be having this cookie only accessible from a http connection. Setting this value to true will ensure that the cookie/session will NOT be accessible through JavaScript, java(ex: .jar files) and other non-http/https protocols.

COMMON PITFALLS

Can’t call setCookie() after output has been sent to the browser

Can’t have more than 20 cookies/server

Cookies ONLY persist until the browser closes UNLESS you specify an expiry date: set Cookie(“name”, $value, time() + 3600);

COOKIE AND SESSION LIFETIME

Cookie and sessions do not last forever and nor should they. A cookie can be set for years but the average person will probably switch computers every 4-5 years.When setting the amount of time a session/cookie will last, you are passing in the amount of seconds. So if you want the cookie/session to expire in 5 minutes, set it to ’60*5’;

CONCLUSION

cookies and sessions are two different ways of making data "persistent" on the client.

A session retains data for the duration of the session.

A cookie retains values for as long as you need it to.