Home arrow MySQL arrow Page 2 - Developing Custom PHP Sessions
MYSQL

Developing Custom PHP Sessions


Ever wondered how to make your own session handling functions with PHP? In this article Brian shows us how to do just that using PHP, MySQL and a bit of maths!

Author Info:
By: Brian Rosner
Rating: 3 stars3 stars3 stars3 stars3 stars / 41
July 21, 2002
TABLE OF CONTENTS:
  1. · Developing Custom PHP Sessions
  2. · Developing the Backend
  3. · Creating the Session Functions (contd.)
  4. · Using Our Sessions
  5. · Conclusion

print this article
SEARCH DEVARTICLES

Developing Custom PHP Sessions - Developing the Backend
(Page 2 of 5 )

First off, we need to plan out how we want to run our sessions by creating our table. You can add a separate database for the sessions, but I recommend setting up another table in your main database if you are using one. We'll start by making a new database assuming you want too. Run this set of code in your MySQL console application:

create database session;

create table sessions (
id int(10) NOT NULL AUTO_INCREMENT,
sess_key char(6) NOT NULL,
val varchar(250) NOT NULL,
ip varchar(35) NOT NULL,
access int(25) NOT NULL,
PRIMARY KEY(id)
);


We simply created a new database and table. The "sessions" table will hold all of our sessions that are actively running. As you become more familiar with how to make your own sessions, then you may want to tweak the table to optimize it for your needs.

Now let's take a look at where all of our code will reside and start learning how the sessions will work. We will need to create a new file, and let's name it sess.php. In that new file put the following code:

<?php

$host = "localhost";
$user = "user";
$pass = "pass";
$db = "db";

$dbc = mysql_connect($host,$user,$pass) or die("Cannot establish a connection to the database.");
mysql_select_db($db,$dbc);

class session {

var $key;
var $timeout;
}
?>


Be sure to change the database connection information to match the setup on your server. We have just defined the very basics of our sessions. We created a new class named session and defined two variables that will be our class methods. These two variables will hold the session key and timeout values.

Creating the Session Functions
I will begin by introducing our first class function. The function will be start() and it will initialize the session by generating the session key. It doesn't store anything in the database yet. You can set the timeout for the session when you call it, but it is optional.

// start() will initialize the session by generating the session key or ID
function start($timeout = "") {

// create an array with all the letters of the alphabet
$letters = range("a","z");
// declare the $key variable
$key = "";

// generate our session's key formatted such as #a#aa#
for($i = 0; $i < 6; $i++) {
if(($i == 0) || ($i == 2) || ($i == 5))
$key .= rand(0,9);
if(($i == 1) || ($i == 3) || ($i == 4))
$key .= $letters[rand(0,25)];
}

// store the session's key in a method of the class
$this->key = $key;

// perform a conditional to test if the user defined the timeout and if not store the default value.
if($timeout == "")
$this->timeout = 300; // five minutes
else
$this->timeout = $timeout;

return 0;
}


As you can see from the code above, we have created a new function called start(). The only argument, $timeout, is optional. If you don't set a value then the function will set the default value of 300 seconds (5 minutes) for timing out. If you define it, it must be in seconds for how long the session can be inactive.

Our function also generates a session key that is used to reference the session in the database. The key is based off the format #a#aa#. This function must be called right after you initialize the class in your login script or the script that will register the value to the session. It only needs to be called once.

Our next function is register() and it will take the argument $val and store it into the database. Let's take a look:

// this function will register a value to session. (only one value, see replace() to update the value)
function register($val) {

// if key is not generated run start()
if($this->key == "")
$this->start();

$insert = mysql_query("INSERT INTO sessions (sess_key, val, ip, sec_expire, stamp_expire, access) VALUES ('" . $this->key. "', '" . addslashes($val) . "' , '" . $_SERVER["REMOTE_ADDR"] . "' , " . $this->timeout . "," . (time() + $this->timeout) . "," . time() .");");
// set the cookie that will store the session key
setcookie("sess_key",$this->key,time()+3600);
}


At the start of the function you will see that we test to see if the key has been created or not. If you don't call start() before register() then it will run start(), but you don't get the option of setting the timeout. I've made our query bold so that it will be a little bit easier to read.

The session key, session value, users' IP, all the expiration details and last access information are stored. The access field contains the last time the user accessed the session before the session times out. This is important because the read() function, seen later on, will update that field and if it's not updated it will automatically time out after the specified timeout even if the user is active. Finally, we set a cookie that will contain our session key and will be used for future reference to the database.
blog comments powered by Disqus
MYSQL ARTICLES

- MySQL and BLOBs
- Two Lessons in ASP and MySQL
- Lord Of The Strings Part 2
- Lord Of The Strings Part 1
- Importing Data into MySQL with Navicat
- Building a Sustainable Web Site
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- PhpED 3.2 More Features Than You Can Poke ...
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- Security and Sessions in PHP
- Setup Your Personal Reminder System Using PHP
- Create a IP-Country Database Using PERL and ...
- Developing a Dynamic Document Search in PHP ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials