Working with Cookies and Sessions

If so, then your only choice is cookies.

If you are storing sensitive information, store it in a database and use the cookies to store an ID number to reference the data.

If you do not need semi-permanent data, then sessions are generally preferred — they are a little easier to use, do not require their data to be sent in entirety with each page, and are also cleaned up as soon as your visitor closes his web browser.

USING COOKIESThe setcookie() call needs to be before the HTML form because of the way the web works.

HTTP operates by sending all “header” information before it sends “body” information.

In the header, it sends things like server type example: “Apache”, page size, and other important data.

In the body, it sends the actual HTML you see on the screen.

HTTP works in such a way that header data cannot come after body data — you must send all your header data before you send anybody data at all.

Cookies come into the category of header data.

When you place a cookie using setcookie(), your web server adds a line in your header data for that cookie.

If you try and send cookies after you have started sending HTML, PHP will flag a serious error and the cookies will not get placed.

There are two types to correct this:Put your cookies at the top of your page.

By sending them before you send anybody data, you avoid the problem entirely.

Enable output buffering in PHP.

This allows you to send header information such as cookies whenever you like — even after body data.

The setcookie() function itself takes three main parameters: the name of the cookie, the value of the cookie, and the data the cookie should expire.

For example:setcookie("Name", $_POST['Name'], time() + 315360000)In that example code, setcookie() sets a cookie called Name to the value set in a form element called Name.

It uses time() + 315360000 as its third parameter, which is equal to the current time in seconds plus the number of seconds in a year so that the cookie is set to expire one year from the time it was set.

Once set, the Name cookie will be sent with every subsequent page request, and, PHP will make it available in $_COOKIE.

Users can clear their cookie manually, either by using a special option in their web browser or just by deleting files.

The last three parameters of the setcookie() function allow you to restrict when it’s sent, which gives you little more control:Parameter four which is path allows you to set a directory in which the cookie is active.

Parameter five which is domain allows you to set a subdomain in which the cookie is active.

Parameter six which is secure lets you specify whether the cookie is active.

Once a cookie has been sent, it becomes available to use on the subsequent page looks through the $_COOKIE superglobal array variable.

Using the previous call to setcookie(), subsequent page loads can have their Name value read like this:print $_COOKIE["Name"];USING SESSIONSSessions store temporary data about your visitors and are particularly good when you don’t want that data to be accessible from outside of your server.

They are an alternative to a cookie if the client has disabled cookie access on her machine because PHP can automatically rewrite URL to pass a session ID around for you.

STARTING A SESSIONA session is a combination of a server-side file containing all the data you wish to store, and a client-side cookie containing a reference to the server data.

The file and the client-side cookie are created using the function session_start() — it has no parameter but informs the server that sessions are going to be used.

When you call session_start(), PHP will check to see whether the visitor sent a session cookie.

If it did, PHP will load the session data.

Otherwise, PHP will create a new session file on the server, and send an ID back to visitors to associate the visitor with the new file.

Because each visitor has his own data locked away in his unique session file, you need to call session_start() before you try to read session variable — falling to do so will mean that you simply will not have access to this data.

Furthermore, as session_start() needs to send the reference cookie to the user’s computer, you need to have it before the body of your web page — even before any spaces.

ADDING SESSION DATAAll your session data is stored in the session superglobal array, $_SESSION, which means that each session variable is one element in that array, combined with its value.

Adding the variable to this array is done in the same way as adding variables to an array, with the added bonus that session variables will still be there when your user browses to another page.

To set a session variable, use syntax like this:$_SESSION['var'] = $val;$_SESSION['firstname'] = 'Jim';Older versions of PHP used the function session_register(); however, use of this function is strongly discouraged, as it will not work properly in default installations of PHP 5.

If you have scripts that use session_register(), you should switch them over to using the $_SESSION superglobal, as it is more portable and easier to read.

Before you can add any variables to a session, you need to have already called the session_start() function.

READING SESSION DATAOnce you have put your data away, it becomes available in the $_SESSION superglobal array with the key of the variable name you gave it.

Here is an example of setting data and reading it back out again:$_SESSION['foo'] = 'bar';print $_SESSION[''foo];Unlike cookies, sessions data is available as soon as it sets.

REMOVING SESSION DATARemoving a specific value from a session is as simple as using the function unset(), just as you would for any other variable.

It is important that you unset only specific elements of the $_SESSION array, not the $_SESSION array itself, because that would leave you unable to manipulate the session data at all.

To extend the previous script to remove data, use this:$_SESSION['foo'] = 'bar';print $_SESSION[''foo];unset($_SESSION['foo']);ENDING A SESSIONA session lasts until your visitor closes their browser — if he/she navigates away to another page, then return to your site without having closed their browser, their session will still exist.

You visitor’s session data might potentially last for days, as long as they keep browsing around your site, whereas cookies usually have a fixed lifespan.

If you want to explicitly end a user’s session and delete their data without them having to close their browser, you need to clear the $_SESSION array, then use the session_destroy() function.

The session_destroy() function removes all session data stored on your hard disk, leaving you with a clean slate.

To end a session and clear its data, use this code:session_start();$_SESSION = array();session_destroy();There are two important things to note here.

First, session_start() is called so that PHP loads the user’s session, and second, we use an empty call to the array() function to make $_SESSION an empty array — effectively wiping it.

If session_start() is not called, neither of the following two lines will work properly, so always call session_start().

CHECKING SESSION DATAYou can check whether a variable has been set in a user’s session using isset(), as you would a normal variable.

Because of the $_SESSION, superglobal is only initialized once session_start() has been called, you need to call session_start() before using isset() on a session variable.

FILES VERSUS DATABASEThe session-handling system in PHP is actually quite basic at its core, simply storing and retrieving values from flat files based upon unique session IDs handed out when a session is started.

While this system works very well for small-scale solutions, it does not work too well when multiple servers come to play.

The problem is down to location, where should session data be stored?If session data is stored in files, the files would need to be in a shared location somewhere — not ideal for performance or locking reason.

However, if the data is stored in a database, that database could then be accessed from all machines in the web server cluster, thereby eliminating the problem.

PHP’s session storage system was designed to be flexible enough to cope with this situation.

To use your own solution in place of the standard session handlers, you need to call the function session_set_save_handler(), which takes several parameters.

In order to handle sessions, you need to have your own callback functions that handle a set of events, which are:Session open (called by session_start())Session close (called at page end)Session read (called after session_Start())Session write (called when session data is to be written)Session destroy (called by session_destroy())To handle these six events, you need to create six functions with very specifc numbers of functions and return type.

Then you pass these six functions into session_set_save_handler() in that order, and you are all set.

This sets up all the basic functions, and prints out what gets passed to the function so you can see how the session operations work:function sess_open ($sess_path, $sess_name) { print "Session opened.

."; print "Sess_path: $sess_path."; print "Sess_name: $sess_name."; return true;}function sess_close() { print "Session closed.

."; return true; }function sess_read($sess_id) { print "Session read.

."; print "Sess_ID: $sess_id."; return ''; }function sess_write ($sess_id, $data) { print "Session value written.

."; print "Sess_ID: $sess_id."; print "Data: $data."; return true; }function sess_destroy ($sess_id) { print "Session destroy called.

."; return true; }function sess_gc($sess_maxlifetime) { print "Session garbage collection called.

."; print "sess_maxlifetime: $sess_maxlifetime. More details

Leave a Reply