Wednesday, May 21, 2008

Using PHP Sessions

Ever wonder how the state of the user is saved while browsing through web pages? An obvious example is when a user buys something online. At the end, when ready to check out, the user gets a list of the items he added earlier to his cart, say some few pages before on the web site.

This is made possible because the website keeps track of the entire user session. In PHP, there is a “Session” feature that allows doing this. It saves the state of the user while browsing through

Sessions are like cookies, with the difference that they are stored on server rather than on client machines. In this way, sessions are more secure than cookies, since information are not exchanged between server and client

Creating PHP Sessions

To create a session in PHP, you need to call “session_start()” at the very beginning of your page, before your html tags.

session_start();

This method causes a session ID to be created and stored in a cookie on the client machine. The file name, by default is PHPSESSID, which can be configured in php.ini. To get this id, just use $phpsessid

If another successive webpage contains the session_start(), PHP checks if a session already exists, and ignores this call if yes.

Accessing and Storing PHP Sessions

You need to register a variable with the session created, as follows

session_register(“session_var”)

You can then use the variable to store the information you need.

$session_var = “Information needed”

Destroying PHP Sessions

Normally, when a user has completed his sale, the entire session should be destroyed for security reasons. First, all variables associated with the session need to be unset, and then the session is destroyed, because only destroying the session does not destroy the session cookie. To unset the variables, we need to call “session_unset()” or $_SESSION= array() . Then we need to destroy the cookies created, which is done as follows:

If (isset($_COOKIE[session_name()])){

setCookie(session_name(), “”, time()-42000, “/”);

session_destroy()

}

No comments: