Monday, August 20, 2007

PHP - Session variable

session : An abstract concept to represent a series of HTTP requests and responses exchanged between a specific Web browser and a specific Web server. Session concept is very useful for Web based applications to pass and share information from one Web page (request) to another Web page (request).
Since the current design of HTTP protocol does not support session concept, all Web server side scripting technologies, including PHP, have designed their own way to support session concept. The key design element of session support is about how to identify a session and how to maintain the session ID (identification). One common way to maintain the session ID is use the cookie technology. The following diagram shows you how to do this:

Server Browser
ID created <-- Request #1 ---
<--- Response #1 --> ID kept as cookie
<-- Request #2 ---> ID send back to server
<--- Response #2 -->
<-- Request #3 --- >ID send back to server
<--- Response #3 -->
......

The session concept should be managed by the server. When the first request comes from a browser on a client host, the server should create a new session, and assigns a new session ID. The session ID will be then send back to the same browser as a cookie. The browser will remember this ID, and send the ID back to the server in the subsequent requests. When the server receives a request with a session ID in them, it knows this is a continuation of an existing session.
When the server receives a request from a browser on a new client host (request without a session ID), the server should not only create a new session ID, it should also create a new session object associated with the new session ID. This session object should become the storage place for different requests of the same session to store and share information.
If there is no subsequent request coming back for a long time for a particular session ID, that session should be timed out. After the session has been timed out, if the browser comes back again with the associated session ID, the server should give an invalid session error.

EXAMPLE:

/* Create new session */
session_start();

/*set session parameter */
session_register("var");
$_SESSION["var"]="test session";

echo $_SESSION["var"];
test session

/*clear session */
session_unregister("var");
unset($_SESSION);
session_destroy();

No comments: