9
http://programmerblog.net How to work with sessions and cookies in PHP

Php ssession - cookies -introduction

Embed Size (px)

Citation preview

Page 1: Php ssession - cookies -introduction

http://programmerblog.net

How to work with sessions and cookies in PHP

Page 2: Php ssession - cookies -introduction

Session Handling by http://programmerblog.net

What Is Session Handling? The Hypertext Transfer Protocol (HTTP) defines the rules used to transfer text, graphics, video, and all other

data via the World Wide Web It is a stateless protocol, meaning that each request is processed without any knowledge of any prior or

future requests A cookie is a small bit of information stored on a viewer's computer by his or her web browser by request

from a web page. The information is constantly passed in HTTP headers between the browser and web server; the browser

sends the current cookie as part of its request to the server and the server sends updates to the data back to the user as part of its response.

limitations on cookie size and the number of cookies allowed, and various inconveniences surrounding their implementation, prompted developers to devise another solution: session handling.

Session handling is essentially a clever workaround to this problem of statelessness. This is accomplished by assigning each site visitor a unique identifying attribute, known as the session ID (SID), Cookies One ingenious means for managing user information actually builds upon the original method of using a

cookie. When a user visits a Web site, the server stores information about the user, such as their preferences, in a

cookie and sends it to the browser, which saves it

Page 3: Php ssession - cookies -introduction

Session Handling by http://programmerblog.net

When a user visits a Web site, the server stores information about the user, such as their preferences, in a cookie and sends it to the browser, which saves it

The second method used for SID propagation simply involves appending the SID to every local URL found within the requested page. This results in automatic SID propagation whenever the user clicks one of those local links. This method, known as URL rewriting.

Drawbacks First, URL rewriting does not allow for persistence between sessions. nothing stops a user from copying that URL into an e-mail and sending it to another user; as long as the

session has not expired

Page 4: Php ssession - cookies -introduction

Session by http://programmerblog.net

The Session-Handling Process PHP can be configured to autonomously control the entire session-handling process The very first task executed by a session-enabled page is to determine whether a valid session already

exists or a new one should be initiated. Configuration Directives Twenty-five session configuration directives are responsible for determining the behavior of PHP’s session-

handling functionality. session.save_handler (files, mm, sqlite, user) The session.save_handler directive determines how the session information will be stored.

– Default value: files

session.save_path (string) Default value: /tmp If session.save_handler is set to the files storage option, then the session.save_path directive must point to

the storage directory. session.name (string) Default value: PHPSESSID

session.auto_start (0|1) session.gc_maxlifetime (integer)

Page 5: Php ssession - cookies -introduction

Session by http://programmerblog.net

Starting a Session session_start() boolean session_start() –

– session_start(); Destroying a Session session_unset() void session_unset() The session_unset() function erases all session variables stored in the current session, Note that this will not completely remove the session from the storage mechanism. session_destroy() boolean session_destroy() The function session_destroy() invalidates the current session by completely removing the session from the

storage mechanism. Retrieving and Setting the Session ID session_id() string session_id ([string sid]) The function session_id() can both set and get the SID. If it is passed no parameter, the function session_id() returns the current SID.

Page 6: Php ssession - cookies -introduction

Session by http://programmerblog.net

session_id() string session_id ([string sid]) The function session_id() can both set and get the SID. If it is passed no parameter, the function

session_id() returns the current SID. echo "Your session identification number is ".session_id(); Creating and Deleting Session Variables It was once common practice to create and delete session variables via the functions session_register() and

session_unregister(), respectively. However, the preferred method involves simply setting and deleting these variable just like any other, except

that you need to refer to it in the context of the $_SESSION superglobal. session_start(); $_SESSION['username'] = "jason"; echo "Your username is ".$_SESSION['username']."."; unset($_SESSION['username']); echo "Username now set to: ".$_SESSION['username']."."; Encoding and Decoding Session Data PHP stores session data in a standardized format consisting of a single string. For example, the contents of

a session consisting of two variables, namely username and loggedon, is displayed here: username|s:5:"jason";loggedon|s:20:"Feb 16 2006 22:32:29";

Page 7: Php ssession - cookies -introduction

Sessions by http://programmerblog.net

Each session variable reference is separated by a semicolon, and consists of three components: the name, length, and value.

name|s:length:"value"; session_encode() session_start(); // Set the variables. These could be set via an HTML form, for example. $_SESSION['username'] = "jason"; $_SESSION['loggedon'] = date("M d Y H:i:s"); // Encode all session data into a single string and return the result $sessionVars = session_encode(); echo $sessionVars; session_decode() session_decode($sessionVars); echo "User ".$_SESSION['username']." logged on at ".$_SESSION['loggedon'].".";

Page 8: Php ssession - cookies -introduction

Cookies by http://programmerblog.net

Cookies Cookies allow your applications to store a small amount of textual data (typically, 4-6kB) on a Web client. There are a number of possible uses for cookies, although their most common one is maintaining session state To set a cookie on the client, you can use the setcookie() function: setcookie(“userid", “1"); This simple function call sets a cookie called “” to a value of 1 for the remainder of the users browser

session, at which time it is automatically deleted. To make a cookie persist between browser sessions, you will need to provide an expiration date. Expiration dates are provided to setcookie() in the UNIX timestamp format (the number of seconds that have

passed since January 1, 1970) setcookie(“userid`", "1", time() + 86400); There are threemore arguments you can pass to setcookie(). They are, in order \ path—allows you to specify a path (relative to your website’s root) where the cookie will be accessible; the browser will only send a cookie to pages within this path. domain—allows you to limit access to the cookie to pages within a specific domain or hostname; note that

you cannot set this value to a domain other than the one of the page setting the cookie (e.g.: the host www.phparch.com can set a

cookie for hades.phparch.com, but not for www.microsoft.com). • secure—this requests that the browser only send this cookie as part of its request headers when communicating under HTTPS.

Page 9: Php ssession - cookies -introduction

Cookies by http://programmerblog.net

Accessing Cookie Data

PHP places cookies in the $_COOKIE superglobal array. if ($_COOKIE[’hide_menu’] == 1) {

// hide menu }

Cookie values must be scalar; of course, you can create arrays using the same array notation that we used for $_GET and $_POST: setcookie("test_cookie[0]", "foo"); setcookie("test_cookie[1]", "bar"); setcookie("test_cookie[2]", "bar"); $_COOKIE[’test_cookie’] will automatically contain an array. You should, however, keep in mind that the amount of storage available is severely limited—therefore, you should keep the amount of data you store in cookies to a minimum, and use sessions instead. Deleting a Cookie There is no way to “delete” a cookie—primarily because you really have no control over how cookies are stored and managed on the client side.

setcookie with an empty string, or in pas date which will effectively reset the cookie. setcookie("hide_menu", false, -3600);