28
1 Cookies & Session Variables

1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

Embed Size (px)

Citation preview

Page 1: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

1

Cookies&

Session Variables

Page 2: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

2

Managing Sessions and Using Session Variables

You may have heard that HTTP, the protocol on which the Web runs, is a “stateless” protocol and, therefore, treats each request for a web page as a unique and independent transaction, with no relationship whatsoever to the transactions that preceded it. While this doesn’t present a problem for most web users, it throws a massive wrench in the works of transaction-based sites, which need to track the activities of each user.

Page 3: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

3

Managing Sessions and Using Session Variables

Consider, for example, the common shopping cart used in web storefronts:

In a “stateless” environment, it is impossible to keep track of the items each user has short listed for purchase, as the stateless nature of the HTTP protocol makes it impossible to identify which transactions belong to which client or user.

Consequently, what is required is a method that makes it possible to “maintain state,” something that allows client connections to be tracked and connection-specific data to be maintained.

A common solution to the problem is to use sessions to store information about each client and track its activities. This session data is preserved for the duration of the visit, and is usually destroyed on its conclusion.

Page 4: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

4

Managing Sessions and Using Session Variables

PHP has included built-in session support since PHP 4.0. Client transactions are identified through unique numbers; these identifiers are used to re-create each client’s prior session environment whenever required. The session identifier may be stored on the client in a cookie or it may be passed from page to page in the URL.

Page 5: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

5

Creating a Session and Registering Session Variables

In PHP, the session_start() function is used to create a client session and generate a session ID. Once a session has been created, it becomes possible to register any number of session variables; these are regular variables which can store textual or numeric information and can be manipulated by standard PHP functions, but are unique to each client. In a PHP script, session variables may be registered as key-value pairs in the special $_SESSION associative array.

When cookies are used to store session data—the most common case— the session_start() function must be called before any output is generated by the script (and that includes the starting <html> tag). This is because of restrictions in the HTTP protocol that require cookies and other headers to be sent before any script output.

Page 6: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

6

Creating a Session and Registering Session Variables

To see how sessions and session variables work, examine the following script, which creates a new client session and registers two session variables:

<?php // first page // create a session session_start(); // register some session variables $_SESSION['username'] = 'deathsbane'; $_SESSION['role'] = 'admin'; ?>

In this example username and role are the two session variables.

Page 7: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

7

Creating a Session and Registering Session Variables

On subsequent pages, calls to the session_start() function re-create the prior session environment by restoring the values of the $_SESSION associative array. This can be tested by attempting to access the values of the session variables registered in the previous example:

<?php // second page // re-create the previous session session_start(); // print the value of the session variable // returns 'deathsbane' echo $_SESSION['username']; ?> If in php.ini PHP settings variable session.auto_start=1 then we do not

need session_start().

Page 8: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

8

Destroying Session

To destroy an extant session—for example, on user logout—reset the $_SESSION array, and then use the session_destroy() function to erase session data.

<?php // re-create session session_start(); // reset session array $_SESSION = array(); // destroy session session_destroy(); ?>

Before you can destroy a session with session_destroy(), you need to first re-create the session environment (so there is something to destroy) with session_start(). This probably seems counterintuitive, and it is, but there isn’t much you can do except grin and bear it.

Page 9: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

9

Additional Session Functions session_register

accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

As an Example:

$barney = "A big purple dinosaur."; session_register("barney"); $_SESSION["zim"] = "An invader from another planet.";

Page 10: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

10

Additional Session Functions(Ctd) session_is_registered Find out whether a global variable is

registered in a session. session_is_registered() returns TRUE if there is a global variable with the name name registered in the current session.

Page 11: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

11

Additional Session Functions(Ctd) session_unregister Unregister a global variable from the current session session_unregister() unregisters the global variable named

name from the current session. This function returns TRUE when the variable is successfully

unregistered from the session. Note: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6

or less) is used, use unset() to unregister a session variable.

This function does not unset the corresponding global variable for name, it only prevents the variable from being saved as part of the session. You must call unset() to remove the corresponding global variable.

Page 12: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

12

Additional Session Functions(Ctd) session_unset   Free all session variables The session_unset() function frees all

session variables currently registered. Note: If $_SESSION (or

$HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use unset() to unregister session variable.

i.e. $_SESSION = array();

Page 13: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

13

Cookies

A cookie is a small piece of information that is retained on the client machine, either in the browser’s application memory or as a small file written to the user’s hard disk.

It contains a name/value pair—setting a cookie means associating a value with a name and storing that pairing on the client side.

Getting or reading a cookie means using the name to retrieve the value.

Page 14: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

14

Cookies

In PHP, cookies are set using the setcookie() function, and cookies are read nearly automatically.

In PHP4.1 and later, names and values of cookie variables show up in the superglobal array $_COOKIES, with the cookie name as an index, and the value as the value it indexes.

Page 15: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

15

Cookies

There is just one cookie-related function, called setcookie(). Table below shows its arguments,in order, all but the first of which are optional.

boolean setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]]) [ means optional

setcookie returns true if cookie is created.

In the comig slide, you will find these arguments.

Page 16: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

16

Arguments of setcookie() Function

Page 17: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

17

Samples on Cookies

setcookie(‘membername’, ‘timboy’); This sets a cookie called membername, with a value

of timboy. Because there are no arguments except for the first two, the cookie will persist only until the current browser program is closed, and it will be read on subsequent page requests from this browser to this server, regardless of the domain name in the request or where in the Web root file hierarchy the page is served from.

The cookie will also be read regardless of whether the Web connection is secure.

Page 18: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

18

Samples on Cookiessetcookie(‘membername’, ‘troutgirl’, time() + (60 * 60 * 24),“/”, “www.troutworks.com”, 1);

This sets the cookie to have the value ‘troutgirl’ and would overwrite the previous example’s value if it had been set by a previous page.

The expiration time is set to 86,400 seconds (or 1 day) after the current time.

The path argument is given the most inclusive path possible(“/”), so this cookie will still be read regardless of where it is in the Web directory hierarchy.

The host argument is set to ‘www.troutworks.com’, which means that subsequent page views will not cause the cookie to be read unless the user actually is making a request of that host.

Finally, the last argument specifies that this cookie will only be read or written over a secure socket connection. (If the very connection used by this page is not secure, presumably the cookie will not be set at all.)

Page 19: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

19

Samples on Cookies You may also set array cookies by using array

notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

setcookie ("cookie[three]", "cookiethree"); setcookie ("cookie[two]", "cookietwo"); setcookie ("cookie[one]", "cookieone"); if (isset ($cookie)) { while (list ($name, $value) = each ($cookie)) { echo "$name == $value<br>\n"; } }

Page 20: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

20

Reading Cookies Cookies that have been successfully set in a

browser or user’s machine will automatically be read on the next request from that browser.

This has the following effects: In PHP4.1 and later, the cookie’s name/value pair will be

added to the superglobal array $_COOKIE, as though we had evaluated $_COOKIE[‘name’] = value.

So, for example, you can set a cookie as follows: setcookie(‘membername’, ‘timboy’);

This means that, on a later page access, you might be able to print the value again as easily as this: $somevar = $_COOKIE[‘membername’];

print(“The member name is $somevar<BR>”);

Page 21: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

21

Reading Cookies If you set a cookie in a given script, it won’t be set on the client until that

page (and its HTTP headers) are sent off to the client, which is too late for you to be able to take advantage of it in that very script. This means that the corresponding global variable won’t be available to you until the next page request.

The following code typically does not work as you might expect: setcookie(‘membername’, ‘timboy’); print(“I set a cookie! Now I will grab the value<BR>”); // (WRONG - the following membername will most likely be blank) $membername = $_COOKIE[‘membername’]; print(“The member name is $membername<BR>”);

This is because, as the preceding Note points out, the cookie will not be set until the current page’s worth of HTTP headers arrives at the client. Because that has not yet happened in this example, and the variable $membername has not been otherwise set, that variable will probably produce an empty string in the preceding print statement.

Page 22: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

22

Reading Cookies

The following code gets it right: $cookievalue = ‘timboy’; setcookie(‘membername’, $cookievalue); print(“I set a cookie for the benefit of future pages<BR>”); // (RIGHT - only print variables that this page actually set) print(“Its name is membername, its value is

$cookievalue<BR>”);

Any subsequent scripts that are loaded into the same browser can now refer to $_COOKIES[“$membername”].

Page 23: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

23

Deleting Cookies

No real way to do this.

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Only your browser is able to delete cookies.

Examples follow how to delete cookies sent in previous example: setcookie() delete examples// set the expiration date to one

hour ago setcookie ("TestCookie", "", time() - 3600); setcookie ("TestCookie", "", time() - 3600,

"/~rasmus/",".utoronto.ca",1);

Page 24: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

24

Cookie Pitfalls -Cookie Refusal Finally, be aware that setcookie() makes no guarantees that any cookie

data will, in fact, be accepted by the client browser—setcookie() just agrees to try, by sending off the appropriate HTTP headers.

What happens after that is up to the client, and the client may be an older browser that does not accept cookies or a browser whose user has intentionally disabled cookies.

The setcookie() function does not even return a value that indicates acceptance or refusal of the cookie. If you think about it, this is imposed by the timing of the script execution and the HTTP protocol.

First, the script executes (including the setcookie() call), with the result that a page complete with HTTP headers is sent to the client machine. At this point, the client browser decides how to react to the cookie-setting attempt. Not until the client generates another request can the server receive the cookie’s value and detect whether the cookie setting attempt was successful.

The implication of this for scripting is that you must always ensure that something reasonable happens, even in cases where setcookie() is called without success.

One common technique is to set a test cookie with the name CookiesOn and then check on a subsequent page load if the $_COOKIE[‘CookiesOn’] variable has been set.

Page 25: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

25

Cookie Pitfalls –Reverse Order Interpretation As with most HTTP commands, calls to setcookie() may actually

be executed in the opposite order from how they appear in your PHP script, but it depends on the particular browser your user is running and the version of PHP you’re using. This means that a pair of successive statements like the following probably have the counterintutive result of leaving the “mycookie” cookie with no value, because the unsetting statement is executed second. setcookie(“mycookie”);// get rid of the old value (WRONG) setcookie(“mycookie”, “newvalue”);// set the new value

(WRONG)

There is no need to remove a cookie before setting it to a different value—simply set it to the desired new value. Among other things, this means that the confusing reverse order of interpretation of setcookie() calls should not usually matter—if the effect depends on the order,it may mean that you are doing something wrong (or at least something unnecessary).

Page 26: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

26

Cookie Pitfalls- Sending Something else First The single most common error in using cookies is trying to set a cookie

after some regular HTML content has already been generated. The reason this doesn’t work is that the HTTP protocol requires headers

to be sent before the content of the HTML page itself—they can’t be intermixed.

As soon as any regular content is generated, PHP figures that it must already know about all headers of interest, and so it sends them off and then begins the transmission of HTML content. If it encounters a cookie (or other header information) later on, it is too late, and an error is generated.

It’s surprisingly easy to write code that violates this prohibition. Consider the following:

<?php /* A subtle, insidious cookie error */ echo “Hello”; setcookie(‘mycookie’, ‘myvalue’); </html>

generates error because we send Hello as the output first.

Page 27: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

27

Sending HTTP Header (header() ) The setcookie() call provides a wrapper around a

particular usage of HTTP headers. In addition, PHP offers the header() function, which you can use to send raw, arbitrary HTTP headers.

You can use this function to roll your own cookie function if you like, but you can also use it to take advantage of any other kind of header-controlled functionality.

The syntax of header() is as simple as it can be: It takes a single string argument, which is the header to be sent.

Sending HTTP before any real page content apply to the header() function as well.

Page 28: 1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a

28

Redirection through Header()

One useful kind of HTTP header is “Location:”, which can act as a redirector. Simply put a fully qualified URL after the “Location:” string, and the browser will start over again with the new address instead. Here’s an example:

<?php if (IsSet($_GET[‘gender’]) && ($_GET[‘gender’] == “female”)){ header(“Location: http://www.example.com/secret.php”); exit;} ?> <HTML><HEAD><TITLE>The inclusive page</TITLE></HEAD></HTML><BODY> <H3>Welcome!</H3> We welcome anyone to this page, even men! Talk amongst yourselves. </BODY></HTML>

If we simply enter the URL for this page (www.example.com/inclusive.php), we will see the rendering of the HTML at the bottom of the script. On the other hand, if we include the right GET argument (www.example.com/inclusive.php?gender=female), we find ourselves redirected to a different page entirely.

Note that this is significantly different from selectively importing contents with the include() statement—we actually end up browsing a different URL than the one we typed in, and that new Web address is what shows up in the Location or Address bar of your browser.

This kind of redirection can be useful when you want the structure of your Web site to conditionally branch without having to make the user explicitly choose different links.

It is possible to use Basic Authentication throught headers (not available in CGI version on IIS) (beyond the scope of this course)