Our 6 functions will now work against a MySQL database:
- sess_open($sess_path, $session_name);
We need to connect to the MySQL database here using mysql_pconnect(),
and then selecting the session database using mysql_select_db(). The
$sess_path and $session_name parameters are irrelevant but we have
to keep them. - sess_close();
We are opening a persistent connection to MySQL so we don’t do anything
in this function. - sess_read($key);
A simple SELECT statement will do the trick, we want to read the
session data for the given key, and we can specify that the expiry
timestamp must be in the future. - sess_write($key, $val);
Writing a session is a little bit trickier. We first try to save the
session into the database using an INSERT statement. If that fails
(from a Primary Key constraint) then that means the key already exists,
so then we have to write an UPDATE statement instead. - sess_destroy($key);
Destroying a session is easy, we just delete the session key from
the database. - sess_gc($maxlifetime);
Garbage collection is easy as well, we just have to delete all the
expired sessions (where the expiry timestamp is in the past) from
the database.
Now we’ve got a MySQL session handler, pretty easy wasn’t it?
Conclusion
This concludes this little tutorial, hopefully you have a good feel for how to
extend the session handling functions in PHP4. The examples here are just simple
ones to demonstrate how you would do it, extend them to accomodate your needs and
if you find any bugs, please let me know 🙂
extend the session handling functions in PHP4. The examples here are just simple
ones to demonstrate how you would do it, extend them to accomodate your needs and
if you find any bugs, please let me know 🙂