The ‘Statelessness’ Problem

The web is ‘statelessness’. That is after a web server has ‘served’ a page your connection to the server is closed and it no longer cares you exist. Knowing who is connected to a page is obviously useful for web applications. For example, it allows pages to be personalized and is essential for features such as shopping carts.

The ‘statelessness’ can be overcome by making users register and then passing information from one page to another using a URL query string. This method is unsatisfactory for the user, insecure and time consuming to implement (as every page in your web site would need some $_GET or $_REQUEST variable handling)

Two alternative approaches are cookies and sessions.

Cookies

Cookies work by storing data on the user’s machine when they visit a page. That is the data is stored on the user’s own machine, the web server writes data to the client computer via the browser. As this is done by the browser the user can change their browser settings to block cookies and stop a web server writing data to it. Cookies will only therefore work on browsers that have cookies enabled. Most web users work with cookies ‘on’ but be aware they can and are switched off by some users. As such when using cookies you will need to test for their presence.
Testing for Cookies

To define a cookie use setcookie(). You must ensure that this function is before any output from a script as cookies are set via the HTTP headers of a HTML document. Any output here includes whitespacing. If setcookie() appears after any output then an error will occur.

Warning: If you place setcookie() after any outputs from echo or print it will fail. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).

This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

The setcookie() function and $_COOKIE

setcookie(string CookieName, string CookieValue, int CookieExpireTime, path, domain, int secure);

CookieName:
The name of the cookie.
CookieValue:
The value of the cookie. This value is stored on the clients computer; do not store sensitive information.
CookieExpireTime:
The time the cookie expires in seconds. Thus ‘time()+60*60*24*10’ will set the cookie to expire in 10 days. If not set, the cookie will expire at the when the browser closes (end of the session).
Path:
directory under web server this cookie is for. Default is to the directory of the requested page.
Doman:
The domain name this cookie can be used under. Default is the domain of the requested page. The domain must have two '.' in it, so if you decide to specify you're top level domain, you must use ".mydomain.com".
Secure:
If set to '1', indicates that the cookie should only be transmitted over a secure HTTPS connection.

Please note that cookies will not become visible until the next loading of a page that the cookie should be visible for. To call the cookie use $_COOKIE['mycookie'].

setcookie("visitor", $_POST[‘login’]);

The above code creates a cookie ‘visitor’ to hold a login value. No expiration time is set so the cookie will expire when the browser is closed.

setcookie("count", $count, time()+600);

The above code creates a cookie ‘count’. This takes it values from a variable $count. The expiration time is 600 seconds (10 minutes) from the current time.

Use isset() in an if condition to check for the presence of a cookie.

if(isset($_COOKIE["count"])) {
..
}

Tip: When changing the value of an existing cookie use setcookie() to re-set/re-create the cookie with the same name.

Removing Cookies

Cookies will expire on the date set via setcookie(). If you do not set an expiry that then when the browser is closed the cookies are removed. To remove a cookie via your code you need to re-set the cookie with a negative expiry date ie a date in the past.

setcookie("myname", '', time()-600);

Cookie Settings in Browsers

Whether cookies will work with your application depends on whether the client browser will accept the cookie. The user can choose to reject cookies through settings in the browser.

For example with to change cookie support in Internet Explorer select Tools > Internet Options and choose the Privacy tab.

Use the slider to change the privacy setting. If this slider is moved to the top the setting is ‘Block All Cookies’.

In Mozilla Firefox similar settings are accessed by selecting Tools > Options and choosing the Privacy tab. This has a cookie tab where cookies can be blocked.

Working with Sessions

Sessions can be used as an alternative to cookies. Whilst cookies are stored on the client machines hard disk, a session is generally stored on the web server.

A session is available as long as the browser is opened.

Every page that makes use of sessions MUST begin with the following.

<?php
session_start();
?>

If no session exists this commands starts one, if one is already started this command recalls values in this session such that they can be displayed via the $_SESSION global array.

Session variables are set using the normal variable assignment method.

$_SESSION['user'] = $_POST['userID'];

To remove session variables use:

<?php
session_start();
unset($_SESSION['user']);
?>

Sessions versus Cookies

As the end result is the same for the user which is the better option? Sessions are generally considered to be more secure as the key data is stored on the server. They also allow you to store more data. Cookies on the other hand require less of the server. However, the irony is that by default, sessions actually use cookies. That is they store a session ID as a cookie on the browser. This session ID then relates to a value stored on the server.

Leave a Comment