What’s a php session anyway?

Posted by Jiltin     18 October, 2008    666 views   

This is not my original php program. Since I find this is very useful for php programming, I got this from “Site With The Lamp” and reproduced for my reference.

=================================================================

A web server is not expected to remember who you are. After a browser retrieves a web page it closes the connection to the web server. (This is not strictly true with HTTP 1.1 but it has little significance for us.) What all this means is that if you logged into a website and tried access your personal information, the webserver by itself wouldn’t know that you are already logged in and wouldn’t give you access to this information. The fact that this doesn’t usually happen is thanks mainly to sessions.

In contrast other protocols such as IMAP or POP3 when you open a connection it’s kept open until you log out or get timed out due to inactivity. All your mail retrival and folder management would be done with this open IMAP connection and the server remembers who you are.

So in short web applications make use of sessions to remeber who are instead of making use of an open socket connection as many other protocols do.

Many people have come to believe that sessions and cookies are one and the same, that is not correct, cookies are merely the most common implementation of sessions. With cookies the persistant data is stored on the client computer. The browser is expected send the cookie to the server with each request.

There are session managements systems where the data is stored on the webserver instead of on the client. This is usually considered more secure than cookies since the data is not passed back and forth between the user and the server and therefore it’s less likely to be intercepted.

The first version of megaupload used cookies for persistence, but lots of developers who downloaded the software wanted them removed as a result later versions uses only server side storage.

In a previous article we had a look at sessions; what they are and what they are not. We discussed how saving session data at the server is far more secure than using cookies.

When keeping session variable at the server they are usually placed in files, at a location specified by ssession.save_path, you can use a call to phpinfo() to find out where that is. Unfortunately if you are on a shared server you cannot rule out the possibility possibility of other users of your server sneaking a peek at these files.

Does that mean sessions should never be used? hardly. You can store your session information in a table of your database and effectively protect against peeping toms. In order to do so you need to override the following methods.


	on_session_read()
	on_session_write()
	on_session_destroy()
	on_session_gc()

There are two other functions but they are not as important when you are using a database instead of a file. Before filling out the function bodies let’s look at what our table ought to look like.


	CREATE TABLE sessions (
	session_id varchar(32) NOT NULL default '',
	session_data text NOT NULL,
	session_expiration timestamp NOT NULL,
	PRIMARY KEY  (session_id)

The table is obviously for mysql but you can easily obtain it’s counterpart for postgresql by putting it through the mysql2pgsql converter. The table is populated in the on_session_write() method and the data is read back in on_session_read(). One very important factor to note is that you cannot use echo or similar calls to produce debugging output from with in the on_session_write() method. You have to use error_log() instead.

In the next step we need to register our session handler functions using the session_set_save_handler method call then you can safely follow up with the session_start() method as you normally would.

	
	session_set_save_handler("on_session_start",   "on_session_end",
				"on_session_read",    "on_session_write",
				"on_session_destroy", "on_session_gc");
	

Even though the session_set_save_handler() has six different parameters only the last four are really usefull to us.

============================================

<?

mysql_connect("localhost","user","pass");
mysql_select_db("mydb");

function on_session_start($save_path, $session_name) {
	error_log($session_name . " ". session_id());
}

function on_session_end() {
	// Nothing needs to be done in this function
	// since we used persistent connection.
}

function on_session_read($key) {
	error_log($key);
	$stmt = "select session_data from sessions ";
	$stmt .= "where session_id ='$key' ";
	$stmt .= "and unix_timestamp(session_expiration) > unix_timestamp(date_add(now(),interval 1 hour))";
	$sth = mysql_query($stmt);

	if($sth)
	{
		$row = mysql_fetch_array($sth);
		return($row['session_data']);
	}
	else
	{
		return $sth;
	}
}
function on_session_write($key, $val) {
	error_log("$key = $value");
	$val = addslashes($val);
	$insert_stmt  = "insert into sessions values('$key', ";
	$insert_stmt .= "'$val',unix_timestamp(date_add(now(), interval 1 hour)))";

	$update_stmt  = "update sessions set session_data ='$val', ";
	$update_stmt .= "session_expiration = unix_timestamp(date_add(now(), interval 1 hour))";
	$update_stmt .= "where session_id ='$key '";

	// First we try to insert, if that doesn't succeed, it means
	// session is already in the table and we try to update

	mysql_query($insert_stmt);

	$err = mysql_error();

	if ($err != 0)
	{
		error_log( mysql_error());
		mysql_query($update_stmt);
	}
}

function on_session_destroy($key) {
	mysql_query("delete from sessions where session_id = '$key'");
}

function on_session_gc($max_lifetime)
{
	mysql_query("delete from sessions where unix_timestamp(session_expiration) < unix_timestamp(now())");
}

// Set the save handlers
session_set_save_handler("on_session_start",   "on_session_end",
			"on_session_read",    "on_session_write",
			"on_session_destroy", "on_session_gc");

session_start();
?>
=======================================================================

Following Google Searches Lead To This Post:
PHP on_session_gc

Post to Twitter  Post to Delicious  Post to Digg    Post to StumbleUpon

Categories : Web & Scripts Tags : , ,

Comments

No comments yet.


Leave a comment

(required)

(required)